Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

  1. Create LinkedList in Rust

  2. Heap in Rust 2.1. Create a new class and make sure you can change how heap sorts the data

  3. BST in Rust 2.2 Use the same class as above and make sure how you can change the sroting

  4. Adjacency matrix 4.1 Why bfs time complexity is (adjancy matrix). What is the memory complexity? 4.2 Why dfs time complexity and memory complexity is and O(n.m) respectfully

  5. Graph in rust

Ahmad Mansouri

Rust Cheatsheet

Rust book itself

Neetcode & corresponding notes

Leetcode

pub fn integers() {
    println!("-----------------------Testing Integers---------------------");
    let my_i32 = 256_i32; // This is 0x0000_0100

    assert_eq!(my_i32, 256_i32);
    assert_eq!(my_i32.isqrt(), 16_i32);
    assert_eq!(my_i32.pow(2), 256_i32 * 256_i32);
    assert_eq!(my_i32.swap_bytes(), 0x00010000_i32);
    assert_eq!(my_i32.reverse_bits(), 0x0080_0000_i32);
    assert_eq!(my_i32.rotate_left(1), 0x0000_0200_i32);

    assert_eq!(my_i32.checked_rem(16i32), Some(0));
    assert_eq!(0x80_u8.checked_rem(0x00_u8), None);
    // assert_eq!((-128i8).checked_rem(0xff_i8), None); This line will not compile. Rust first
    // attempts to fit 128 into an i8 which do not.
    assert_eq!(i8::MIN.checked_rem(-1), None);
    assert_eq!(my_i32.to_string(), "256");
    assert_eq!(my_i32.max(257_i32), 257_i32);
    assert_eq!(my_i32.count_ones() + my_i32.count_zeros(), 32_u32);
    assert_eq!(i32::MIN, -2 * 2i32.pow(30));
    assert_eq!(my_i32.leading_ones(), 0);
    assert_eq!(my_i32.leading_ones(), 0);
    assert_eq!(i32::MIN.to_string().parse(), Ok(i32::MIN));

    println!("All assesrtions PASSED");
}

fn main() {
    integers();
}
pub fn strings() {
    println!("--------------- Testing Strings -------------------");
    let mut my_string = "Hello".to_string();
    assert_eq!(my_string.len(), 5);

    let _ = String::from("Hello");

    //Empty string
    let _empty_string = String::new();

    my_string.push_str(" World");
    assert_eq!(my_string, "Hello World");
    assert!(!my_string.is_empty());
    let my_string_2 = format!("{}-{}", my_string, my_string);
    assert_eq!(my_string_2, "Hello World-Hello World");

    my_string.push('s');
    assert_eq!(my_string, "Hello Worlds");

    let s_unicode = String::from("你好世界");
    for c in s_unicode.chars() {
        println!("{}", c);
    }

    let my_slice = &my_string;
    for d in my_slice.chars() {
        println!("{}", d);
    }
    
    for d in my_string.bytes() {
        println!("{}", d);
    }

    for d in "احمد".char_indices() {
        println!("Index {} : Char {} ", d.0, d.1); // 0, 2, 4, 6
    }
    
    assert!(my_string.contains("Hello"));
    assert!(my_string.starts_with("Hello"));
    assert!(my_string.ends_with("Worlds"));
   
    assert_eq!(my_string.find("Worlds"), Some(6));
    
    my_string = my_string.replace("l", "L");
    assert_eq!(my_string, "HeLLo WorLds");
    my_string = my_string.replacen("L", "l", 1);
    assert_eq!(my_string, "HelLo WorLds");
    
    my_string = my_string.to_lowercase();
    assert_eq!(my_string, "hello worlds");
    my_string = my_string.to_uppercase();
    assert_eq!(my_string, "HELLO WORLDS");

    my_string = format!(" {} ", my_string);
    assert_eq!(my_string.trim_start(), "HELLO WORLDS ");
    assert_eq!(my_string.trim_end(), " HELLO WORLDS");
    assert_eq!(my_string.trim(), "HELLO WORLDS");

    
    assert!(my_string == " HELLO WORLDS ");
    assert!(my_string.eq(" HELLO WORLDS "));
    assert!(my_string.eq_ignore_ascii_case(" hEllo worlds "));
    
    ////////////////////////////////////////////////////////////////
    println!("All Asserstions PASSED");
}

fn main() {
    strings();
}
#![allow(unused)]
fn main() {
use std::cmp::Ord;
use std::boxed::Box;

#[derive(Debug)]
struct TreeNode<T> {
    val: T,
    left: Option<Box<TreeNode<T>>>,
    right: Option<Box<TreeNode<T>>>,
}

#[derive(Debug)]
pub struct BST<T> {
    root: Option<Box<TreeNode<T>>>,
}


impl<T: Ord> TreeNode<T> {
    fn new(val: T) -> Self {
        TreeNode {
            val,
            left: None,
            right: None,
        }
    }

    fn insert(&mut self, val: T) {
        if val < self.val {
            match self.left {
                Some(ref mut left_node) => left_node.insert(val),
                None => self.left = Some(Box::new(TreeNode::new(val))),
            }
        } else if val > self.val {
            match self.right {
                Some(ref mut right_node) => right_node.insert(val),
                None => self.right = Some(Box::new(TreeNode::new(val))),
            }
        }
        // Duplicate values are ignored
    }
}

impl<T: Ord> BST<T> {
    pub fn new() -> Self {
        BST { root: None }
    }

    pub fn insert(&mut self, val: T) {
        match self.root {
            Some(ref mut node) => node.insert(val),
            None => self.root = Some(Box::new(TreeNode::new(val))),
        }
    }
}
}
fn static_arrays() {
    let sarr: [i32; 5] = [12, 13, 14, 15, 16];
    sarr.contains(&34);
    let first = sarr[0];
    println!("fist element of the array is {}", first);
    assert_eq!(sarr.len(), 5);
    let safe_element = sarr.get(10);
    assert_eq!(safe_element, None);
    println!("Ahmad MAAAAAAAAAAAAAAAAAAAAAAAAAAAA");
    let contac = [sarr, sarr].concat();
    let first2 = contac.first();
    assert_eq!(first2, Some(&12));
    let last = contac.last();
    assert_eq!(last, Some(&16));
    let mut a = [sarr, sarr].join(&12);

    for (i, item) in a.iter().enumerate() {
        println!("{i} : {item}");
    }

    for itm in a.iter_mut() {
        *itm += 10;
    }

    if let Some(&val) = sarr.iter().max() {
        println!("{}", val);
    }

}

fn dynamic_arrays() {}

pub fn arrays() {
    static_arrays();
    dynamic_arrays();
}

fn main() {
    arrays();
}

fn main() {
    println!("Hello, world!");

    let mut v = vec![1, 2, 3];

    for item in v.iter() {
        println!("{}", item);
    }

    let sum: i32 = v.iter().sum();
    println!("Sum = {}", sum);

    for item in v.iter_mut() {
        println!("{}", item);
        *item += 1;
    }

    let s: Vec<i32> = v.into_iter().filter(|&item| item % 2 == 0).collect();
    let s1 = s.iter().all(|&item| item % 2 == 0);

    if s1 {
        println!("Yes");
    } else {
        println!("NO");
    }

    let s2: Vec<i32> = s.iter().map(|&item| item+1).collect();
    for item in s2.iter() {
        println!("{}", item);
    }
}

Of course. This is an excellent question because it gets to the heart of Rust's ownership and borrowing system. Thinking about this without a compiler forces you to understand the underlying principles.

Here is a guide and a mental model to help you decide when to use &.

The Core Question: Ownership vs. Borrowing

The fundamental question you must always ask yourself is:

"Does this piece of code need to own the data, or does it just need to use it for a while?"

Owning (T): If the function needs to take the data and become its new owner, you pass the value directly (e.g., my_string). The original owner can no longer use it.

Borrowing (&T or &mut T): If the function just needs to read or modify the data temporarily and then give it back, you pass a reference (e.g., &my_string). The original owner retains ownership and can use the data again after the function call.

The Library Book Analogy (A Mental Model)

Imagine your data is a book.

Giving the book away (Passing by Value: T): You give your only copy of the book to a friend. You no longer have it. Your friend now owns it and can do whatever they want with it, including giving it to someone else.

#![allow(unused)]
fn main() {
// You have the book
let book = String::from("The Rust Programming Language");
// You give it to your friend (the function)
read_and_keep(book);
// You can't read the book anymore, this would be a compiler error!
// println!("{}", book);
}

Letting a friend read your book (Immutable Borrow: &T): You let a friend look at your book. They can read it, but they can't write in it or tear out pages. When they're done, they give it back. You can even let multiple friends read it at the same time. This is the most common and safest way to share.

#![allow(unused)]
fn main() {
// You have the book
let book = String::from("The Rust Programming Language");
// You let a friend read it
glance_at_title(&book);
// You still have the book and can read it yourself.
println!("I still have: {}", book);
}

Letting a friend edit your book (Mutable Borrow: &mut T): You let one, and only one, trusted friend borrow your book to make corrections. While they have it, nobody else (not even you!) can read or write in it. This ensures there are no conflicting edits. When they're done, they give it back with the changes.

#![allow(unused)]
fn main() {
// You have the book
let mut book = String::from("Programming in Rus");
// You let a friend make a correction
add_character(&mut book);
// You get the edited book back.
println!("The corrected title is: {}", book);
}

A Decision-Making Flowchart (For When You're Coding)

When writing a function signature, ask yourself these questions in order:

Question 1: Will this function modify the data it receives?

YES → You almost certainly need a mutable borrow: &mut T.

Example: A function that appends a suffix to a String.

#![allow(unused)]
fn main() {
// The function needs to change the string in place.
fn append_world(s: &mut String) {
    s.push_str(", world!");
}
}

NO → Go to Question 2.


Question 2: Is the data "cheap" to copy?

Rust has a special trait called Copy. Types that have this trait are simple values (like integers, booleans, floating-point numbers) that live on the stack and are trivial to duplicate.

YES, it's a Copy type (like i32, f64, bool, char, or a tuple of Copy types) → Just pass it by value: T.

It's simpler and often just as fast as a reference because copying a few bytes is instantaneous.

Example: A function that adds two numbers.

#![allow(unused)]
fn main() {
// i32 is a Copy type. It's cheap to copy.
fn add(a: i32, b: i32) -> i32 {
    a + b
}
}

NO, it's complex/large data (like String, Vec<T>, a struct you defined) → Go to Question 3.


Question 3: Does the function need to take ownership of the data?

This usually happens for one of these reasons:

  • The function will store the data in a struct or enum.
  • The function will send the data to another thread.
  • The function's whole purpose is to transform the data and return a new, owned value, consuming the original in the process.

YES, it needs to consume the data → Pass it by value: T.

Example: A Person struct that stores a name. The struct needs to own the String.

#![allow(unused)]
fn main() {
struct Person {
    name: String,
}

impl Person {
    // The Person struct must OWN the name, so we take `String` by value.
    fn new(name: String) -> Self {
        Person { name }
    }
}
}

NO, the function just needs to read the data → Use an immutable borrow: &T.

This is the most common case for complex data. You avoid a potentially expensive copy and you signal that the function will not change the data.

Example: A function that calculates the length of a String.

#![allow(unused)]
fn main() {
// The function only needs to READ the string to find its length.
// It doesn't need to own it or change it.
fn calculate_length(s: &String) -> usize {
    s.len()
}
}

Quick Reference "Cheat Sheet"


Goal Your thought process Syntax Example


Read Only "I just need to look at this data. &T (or fn print_summary(item: &Item) I won't change it." &str)

Modify in "I need to change this data &mut T fn clear_vector(vec: &mut Vec<i32>) Place directly."

Take "I need to store this data in a T fn create_user(name: String) -> User Ownership struct or send it to another (The User struct owns name) thread."

Simple Data "This is an i32 or bool. It's T fn is_positive(num: i32) -> bool (e.g., cheap to copy."
numbers)


Final Rule of Thumb

When in doubt, start with a borrow (&T). It's the most flexible option. If you later find out you need to modify it, change to &mut T. Only take ownership (T) if you have a clear and explicit reason why the function needs to consume the value.

Problem I solved

  1. Two Sum

Note that if you run these two implementation in release mode, the second implementation fails because it does not take into consideration the overflow.

use std::collections::HashMap;

fn main() {
    let data: [i8; 4] = [-128, -1, 12, 13];
    let target = 127;
    if let Some(indice) = two_sum(&data, target) {
        println!("Correct Two Sum found: {indice:?}");
    } else {
        println!("Correct Two Sum did not find a result ")
    }

    if let Some(indice) = two_sum_2(&data, target) {
        println!("Incorrect Two Sum found: {indice:?}");
    } else {
        println!("Incorrect Two Sum did not find a result ")
    }
}

fn two_sum(data: &[i8], target: i8) -> Option<(usize, usize)> {
    let mut my_map: HashMap<i8, usize> = HashMap::new();

    for (idx, item) in data.iter().enumerate() {
        if let Some(val) = target.checked_sub(*item) {
            if let Some(&jdx) = my_map.get(&val) {
                return Some((jdx, idx));
            }
        }
        my_map.insert(*item, idx);
    }
    None
}

fn two_sum_2(data: &[i8], target: i8) -> Option<(usize, usize)> {
    let mut my_map: HashMap<i8, usize> = HashMap::new();

    for (idx, item) in data.iter().enumerate() {
        let val = target - *item;
        println!("{val}");
        if let Some(&jdx) = my_map.get(&val) {
            return Some((jdx, idx));
        }
        my_map.insert(*item, idx);
    }
    None
}
  1. Is Palindrome
#![allow(unused)]
fn main() {
impl Solution {
    pub fn is_palindrome(x: i32) -> bool {
        // 1. Handle edge cases:
        //    a. Negative numbers cannot be palindromes (e.g., -121 reads as 121-).
        //    b. Numbers ending in 0 (e.g., 10, 120) cannot be palindromes unless the number itself is 0.
        //       (If x % 10 == 0 and x != 0, its reversed form would not match, as it wouldn't start with 0).
        if x < 0 || (x % 10 == 0 && x != 0) {
            return false;
        }

        let mut num = x;
        let mut reverted_number = 0;

        // 2. Reverse half of the number:
        // We build `reverted_number` by taking digits from the end of `num`
        // and appending them to `reverted_number`.
        // We stop when `num` becomes less than or equal to `reverted_number`.
        // This means we've processed roughly half of the digits.
        while num > reverted_number {
            reverted_number = reverted_number * 10 + num % 10; // Add the last digit of num to reverted_number
            num /= 10; // Remove the last digit from num
        }

        // 3. Compare the original number (or its first half) with the reversed half:
        //
        // Case A: The original number had an even number of digits.
        // Example: x = 1221
        //   - Iter 1: num = 122, reverted_number = 1
        //   - Iter 2: num = 12, reverted_number = 12
        //   - Loop terminates because num (12) is not > reverted_number (12).
        //   In this case, `num` and `reverted_number` should be exactly equal.
        //
        // Case B: The original number had an odd number of digits.
        // Example: x = 121
        //   - Iter 1: num = 12, reverted_number = 1
        //   - Iter 2: num = 1, reverted_number = 12
        //   - Loop terminates because num (1) is not > reverted_number (12).
        //   In this case, `reverted_number` will have one extra digit (the middle digit)
        //   compared to `num`. We need to remove this middle digit from `reverted_number`
        //   for a correct comparison (e.g., 12 / 10 = 1, which matches `num`).

        num == reverted_number || num == reverted_number / 10
    }
}
}

Given a string s, return true if the s can be palindrome after deleting at most one character from it.

Note: Since it is guaranteed that all characters are English letters, we could use as_bytes()

#![allow(unused)]
fn main() {
impl Solution {
    pub fn valid_palindrome(s: String) -> bool {
        // Use as_bytes() for efficient O(1) indexing.
        // This is safe because the problem guarantees lowercase English letters.
        let bytes = s.as_bytes();
        let mut left = 0;
        let mut right = s.len() - 1;

        while left < right {
            if bytes[left] != bytes[right] {
                // Mismatch found! We must use our one deletion.
                // Check both possibilities:
                // 1. Delete the left character
                // 2. Delete the right character
                return Self::is_palindrome_slice(bytes, left + 1, right) ||
                       Self::is_palindrome_slice(bytes, left, right - 1);
            }
            // No mismatch, shrink the window
            left += 1;
            right -= 1;
        }

        // The loop finished without mismatches,
        // so it was already a palindrome (0 deletions).
        true
    }

    /// Helper function to check if a sub-slice is a palindrome.
    fn is_palindrome_slice(bytes: &[u8], mut left: usize, mut right: usize) -> bool {
        while left < right {
            if bytes[left] != bytes[right] {
                return false;
            }
            left += 1;
            right -= 1;
        }
        true
    }
}
}
#![allow(unused)]
fn main() {
fn merge_alternately_std(word1: String, word2: String) -> String {
    // 1. Efficiency: Pre-allocate the string to its final size.
    // We use .len() (bytes) which is a fast O(1) lower bound.
    // **Note:** both len() and with_capacity are using byte for the size
    let mut result = String::with_capacity(word1.len() + word2.len());

    // 2. Idiomatic: Get char iterators.
    let mut chars1 = word1.chars();
    let mut chars2 = word2.chars();

    // 3. Idiomatic: Loop based on the iterators themselves.
    loop {
        // Use `match` to handle all cases cleanly without unwrap()
        match (chars1.next(), chars2.next()) {
            // Both strings still have chars
            (Some(c1), Some(c2)) => {
                result.push(c1);
                result.push(c2);
            }
            // Only word1 has chars
            (Some(c1), None) => {
                result.push(c1);
                // 4. Idiomatic: Once word2 is done, just extend with the rest
                //    of word1 and break.
                result.extend(chars1);
                break;
            }
            // Only word2 has chars
            (None, Some(c2)) => {
                result.push(c2);
                result.extend(chars2);
                break;
            }
            // Both are empty
            (None, None) => {
                break;
            }
        }
    }

    result
}
}
fn check_same_digits(mut num1: u32, mut num2: u32) -> bool {
    let mut counts = [0; 10];

    while num1 > 0 {
        counts[(num1 % 10) as usize] += 1;
        num1 /= 10;
    }

    while num2 > 0 {
        counts[(num2 % 10) as usize] -= 1;
        num2 /= 10;
    }

    counts.iter().all(|&c| c == 0)
}

fn main() {
    let c = check_same_digits(12, 21);
    if c {
        println!("YES");
    } else {
        println!("NO");
    }
}

LRU Cache in Rust

Problem Statement

Design a data structure that follows the constraints of a Least Recently Used (LRU) cache.

Implement the LRUCache class:

  • LRUCache(int capacity): Initialize the LRU cache with a positive size capacity.
  • int get(int key): Return the value of the key if the key exists, otherwise return -1.
  • void put(int key, int value): Update the value of the key if the key exists. Otherwise, add the key-value pair to the cache. If the number of keys exceeds the capacity from this operation, evict the least recently used key.

The functions get and put must each run in O(1) average time complexity.


Approach

Designing an LRU Cache is a classic problem that tests your understanding of data structures and their performance characteristics.
To achieve O(1) time complexity for both get and put operations, a single data structure like a Vec or a HashMap is insufficient.

The optimal solution involves two data structures:

  1. HashMap for O(1) average time lookups — mapping a key to a node in a linked list.
  2. Doubly-Linked List to maintain the order of usage — allowing O(1) insertion and deletion from anywhere when we have the node.

Strategy

  • The doubly-linked list stores (key, value) pairs in order of recency.
  • The head is the most recently used item, the tail is the least recently used.
  • The HashMap maps a key to its corresponding Node in the list.

Operations

put(key, value):

  • If the key exists: update the node's value and move it to the head.
  • If the key doesn't exist: create a node.
  • If capacity is reached: evict the tail node (LRU) and remove it from the HashMap.
  • Insert the new node at the head.

get(key):

  • If the key exists: move the node to the head and return its value.
  • If not: return -1.

Rust Implementation

We use Rc<RefCell<T>> and Weak<T> to manage shared ownership and prevent reference cycles in the doubly-linked list.

#![allow(unused)]
fn main() {
use std::collections::HashMap;
use std::cell::RefCell;
use std::rc::{Rc, Weak};

// A pointer to a node. Using Rc for shared ownership.
type Link = Option<Rc<RefCell<Node>>>;
// A weak pointer to a node, to prevent reference cycles.
type WeakLink = Option<Weak<RefCell<Node>>>;

// Node in the doubly-linked list
struct Node {
    key: i32,
    value: i32,
    prev: WeakLink,
    next: Link,
}

impl Node {
    fn new(key: i32, value: i32) -> Self {
        Node { key, value, prev: None, next: None }
    }
}

pub struct LRUCache {
    capacity: usize,
    map: HashMap<i32, Rc<RefCell<Node>>>,
    head: Link,
    tail: Link,
}


/** * Note: The provided LeetCode template uses `&self` for `get` and `put`.
 * This is incorrect because these methods need to modify the cache's internal
 * state (the order of the list and the map). We must use `&mut self`.
 */
impl LRUCache {

    pub fn new(capacity: i32) -> Self {
        LRUCache {
            capacity: capacity as usize,
            map: HashMap::with_capacity(capacity as usize),
            head: None,
            tail: None,
        }
    }
    
    pub fn get(&mut self, key: i32) -> i32 {
        if let Some(node_rc) = self.map.get(&key).cloned() {
            // The node exists. Move it to the front of the list.
            self.detach_and_move_to_front(&node_rc);
            // Return its value.
            let value = node_rc.borrow().value;
            value
        } else {
            // The key doesn't exist.
            -1
        }
    }
    
    pub fn put(&mut self, key: i32, value: i32) {
        if let Some(node_rc) = self.map.get(&key).cloned() {
            // Key already exists. Update value and move to front.
            node_rc.borrow_mut().value = value;
            self.detach_and_move_to_front(&node_rc);
        } else {
            // Key is new. Check capacity.
            if self.map.len() == self.capacity {
                // Evict the least recently used item (the tail).
                if let Some(tail_rc) = self.tail.take() {
                    let key_to_evict = tail_rc.borrow().key;
                    self.map.remove(&key_to_evict);
                    // Update the tail to be the previous node.
                    if let Some(prev_weak) = tail_rc.borrow_mut().prev.take() {
                        if let Some(prev_rc) = prev_weak.upgrade() {
                            prev_rc.borrow_mut().next = None;
                            self.tail = Some(prev_rc);
                        }
                    } else {
                        // The list is now empty.
                        self.head = None;
                    }
                }
            }
            
            // Create the new node and add it to the front.
            let new_node_rc = Rc::new(RefCell::new(Node::new(key, value)));
            self.push_front(&new_node_rc);
            self.map.insert(key, new_node_rc);
        }
    }

    // --- Helper Methods for List Manipulation ---

    /// Moves an existing node to the front of the list.
    fn detach_and_move_to_front(&mut self, node_rc: &Rc<RefCell<Node>>) {
        // If the node is already the head, do nothing.
        if self.head.as_ref().map_or(false, |h| Rc::ptr_eq(h, node_rc)) {
            return;
        }

        self.detach(node_rc);
        self.push_front(node_rc);
    }

    /// Detaches a node from the list by linking its neighbors.
    fn detach(&mut self, node_rc: &Rc<RefCell<Node>>) {
        let mut node = node_rc.borrow_mut();
        let prev_weak = node.prev.take();
        let next_rc = node.next.take();

        if let Some(prev_node) = prev_weak.as_ref().and_then(|w| w.upgrade()) {
            prev_node.borrow_mut().next = next_rc.clone();
        } else {
            // This was the head node.
            self.head = next_rc.clone();
        }

        if let Some(next_node) = next_rc.as_ref() {
            next_node.borrow_mut().prev = prev_weak;
        } else {
            // This was the tail node.
            self.tail = prev_weak.and_then(|w| w.upgrade());
        }
    }

    /// Pushes a new node to the front (head) of the list.
    fn push_front(&mut self, node_rc: &Rc<RefCell<Node>>) {
        node_rc.borrow_mut().next = self.head.clone();
        node_rc.borrow_mut().prev = None;

        if let Some(old_head) = self.head.as_ref() {
            old_head.borrow_mut().prev = Some(Rc::downgrade(node_rc));
        }
        
        self.head = Some(node_rc.clone());

        if self.tail.is_none() {
            // If the list was empty, this node is both head and tail.
            self.tail = Some(node_rc.clone());
        }
    }
}

/**
 * Your LRUCache object will be instantiated and called as such:
 * let mut obj = LRUCache::new(capacity);
 * let ret_1: i32 = obj.get(key);
 * obj.put(key, value);
 */
}
fn main() {
    let mut result = pascan_triangle(5);

    for (rdx, row) in result.iter().enumerate() {
        for (cdx, col) in row.iter().enumerate() {
            println!("{},{} = {}", rdx, cdx, col)
        }
        println!();
    }
}
fn pascan_triangle(num_rows: i32) -> Vec<Vec<i32>> {
    // If the number of rows is 0, return an empty vector.
    if num_rows == 0 {
        return vec![];
    }

    // Initialize the triangle with the first row.
    let mut triangle = vec![vec![1]];

    // Iterate from the second row up to the desired number of rows.
    for i in 1..num_rows as usize {
        // Get a reference to the previous row.
        let prev_row = &triangle[i - 1];
        // Start the new row with 1.
        let mut new_row = vec![1];

        // Calculate the middle elements of the new row.
        // Each element is the sum of the two elements directly above it.
        for j in 1..prev_row.len() {
            new_row.push(prev_row[j - 1] + prev_row[j]);
        }

        // End the new row with 1.
        new_row.push(1);
        // Add the newly created row to the triangle.
        triangle.push(new_row);
    }

    // Return the complete triangle.
    triangle
}

fn main() {
    let data = vec![String::from("Ahmad"), String::from("Ahmar")];
    let result = longest_common_prefix(data);
    println!("{}", result);
    println!("Hello");
}

fn longest_common_prefix(strs: Vec<String>) -> String {
    let result = String::new();

    if strs.is_empty() {
        return result;
    }

    let first_string = &strs[0];
    let mut char_index = 0;
    for (idx, ch) in first_string.bytes().enumerate() {
        for j in 1..strs.len() {
            let current_string = &strs[j];

            if idx > current_string.len() || current_string.as_bytes()[idx] != ch {
                return first_string[..idx].to_string();
            }
        }
        char_index += 1;
    }
    first_string[0..char_index].to_string()
}
fn main() {
    let samples = vec!["()", "()[]{}", "(]", "([])", "([)]"];
    for sample in samples {
        println!("{} is {}", sample, valid_parentheses(sample));
    }
}


fn  valid_parentheses(s: &str) -> bool {
    let mut stk = Vec::new();
    for ch in s.chars() {
        match ch {
            '{' | '(' | '[' => {
                stk.push(ch);
            }
            ')' => {
                if stk.pop() != Some('(') {
                    return false;
                }
            }
            '}' => {
                if stk.pop() != Some('{') {
                    return false;
                }
            }
            ']' => {
                if stk.pop() != Some('[') {
                    return false;
                }
            }
            _ => (),
        }
    }
    stk.is_empty()
}
fn main() {
    let mut samples = vec![7,1,5,3,6,4];
    println!("{}", best_time_to_buy_and_sell_stock(samples));
}

fn best_time_to_buy_and_sell_stock(prices: Vec<i32>) -> i32 {
    let mut result = 0;
    let mut min = i32::MAX;
    for price in prices {
        result = result.max(price-min);
        min = min.min(price);
    }
    result
}
#![allow(unused)]

fn main() {
fn num_of_unplaced_fruits(fruits: &Vec<i32>, baskets: &Vec<i32>) -> i32 {
    let mut used = vec![false; baskets.len()];
    for &fruit in fruits {
        for (idx, &basket) in baskets.iter().enumerate() {
            if !used[idx] && basket >= fruit {
                used[idx] = true;
                break;
            }
        }
    }
    used.iter().filter(|item| **item != true).count() as i32
}

fn single_number(nums: Vec<i32>) -> i32 {
    let mut result = 0;
    for item in nums {
        result ^= item
    }
    result
}

fn is_anagram(s: String, t: String) -> bool {
    let mut hash_map: HashMap<char, i32> = HashMap::new();

    for ch in s.chars() {
        hash_map
            .entry(ch)
            .and_modify(|count| *count += 1)
            .or_insert(1);
    }

    for ch in t.chars() {
        hash_map
            .entry(ch)
            .and_modify(|count| *count -= 1)
            .or_insert(-1);
    }

    hash_map.iter().filter(|(_, item)| **item != 0).count() == 0
}

fn majority_element(nums: Vec<i32>) -> i32 {
    let mut candidate = 0;
    let mut count = 0;

    for num in nums {
        if count == 0 {
            candidate = num;
        }

        if num == candidate {
            count += 1;
        } else {
            count -= 1;
        }
    }
    candidate
}

fn power_of_three(num: i32) -> bool {
    let mut num = num;
    if num <= 0 {
        return false;
    }
    while (num % 3 == 0) {
        num /= 3;
    }
    num == 1
}



fn roman_to_int(s: String) -> i32 {
    let mut result = 0;
    let mut prev_value = 0;

    for ch in s.chars().rev() {
        let current_value = match ch {
            'I' => 1,
            'V' => 5,
            'X' => 10,
            'L' => 50,
            'C' => 100,
            'D' => 500,
            'M' => 1000,
            _ => 0,
        };
        if current_value < prev_value {
            println!(
                current_value, prev_value
            );
            result -= current_value;
        } else {
            println!(
                current_value, prev_value
            );
            result += current_value;
        }
        prev_value = current_value;
    }

    result
}


pub fn search_insert(nums: Vec<i32>, target: i32) -> i32 {
    if nums.is_empty() {
        return 0;
    }

    let mut low: i32 = 0;
    let mut high: i32 = (nums.len() - 1) as i32;

    // Use a while loop with low <= high
    while low <= high {
        // Use an unsigned type for mid to avoid cast warnings.
        let mid = low + (high - low) / 2;
        let mid_val = nums[mid as usize];

        if mid_val == target {
            return mid;
        } else if mid_val < target {
            // Target is in the right half
            low = mid + 1;
        } else {
            // Target is in the left half
            high = mid - 1;
        }
    }

    // After the loop, `low` is the correct insertion point.
    low
}

fn largest_good_integer(num: String) -> String {
    let mut best = String::new();
    let chars: Vec<char> = num.chars().collect();

    for i in 0..=chars.len().saturating_sub(3) {
        if chars[i] == chars[i + 1] && chars[i] == chars[i + 2] {
            let candidate = chars[i].to_string().repeat(3);
            if candidate > best {
                best = candidate;
            }
        }
    }

    best
}

fn remove_duplicates(nums: &mut Vec<i32>) -> i32 {
    if nums.is_empty() {
        return 0;
    }
    let mut i =0;

    for j in 0..nums.len() {
        if nums[j] != nums[i] {
            i += 1;
            nums[i] = nums[j];
        }
    }
    (i+1) as i32
}


pub fn str_str(haystack: String, needle: String) -> i32 {
        let haystack: Vec<char> = haystack.chars().collect();
        let needle: Vec<char> = needle.chars().collect();
    
        let ns = needle.len();
        let hs = haystack.len();

        if hs < ns {
            return -1;
        }
        println!("ns = {}", ns);
        println!("hs = {}", hs);
    
        'first_loop: for i in 0..=(hs - ns) {
            for j in 0..ns {
                if needle[j] != haystack[i + j] {
                    continue 'first_loop;
                }
            }
            return i as i32;
        }
        -1 
    }
}

fn move_zeroes(nums: &mut Vec<i32>) {
    let mut j = 0;
    for i in 0..nums.len() {
        if nums[i] != 0 {
            nums[j] = nums[i];
            j += 1;
        }
    }
    for i in j..nums.len() {
        nums[i as usize] = 0;
    }
}

fn maximum69_number(num: i32) -> i32 {
    let mut num = num;
    let result = num;

    let mut level: i32 = -1;
    let mut r_level = -1;

    while num > 0 {
        level += 1;
        if num % 10 == 6 {
            r_level = level;
        }
        num /= 10;
    }
    if r_level >= 0 {
        let added_value = 3 * 10i32.pow(r_level as u32);
        return result + added_value;
    }
    result
}
}

Question:

Is the implementation below fine? I am also familiar with .count_ones()

#![allow(unused)]
fn main() {
// Corrected version of your function
// Using u32 is more idiomatic for bitwise operations to avoid sign bit issues
fn hamming_weight_iterative(n: u32) -> i32 {
    let mut result = 0;
    for i in 0..32 {
        if (1 << i) & n != 0 {
            result += 1
        }
    }
    result
}
}

Better Solutions for Calculating Hamming Weight

The main drawback of this method is that it always performs 32 iterations, regardless of the input. If n is 1, it still needlessly checks the 31 other bits.

Here are some better solutions, ordered from a simple improvement to the most optimal approach.


1. Brian Kernighan's Algorithm

This is a classic and very elegant improvement. The trick is to realize that the operation n & (n - 1) clears the least significant set bit (the rightmost '1').

By repeatedly applying this operation until the number becomes 0, you can count exactly how many set bits there were.

How it works:

  • Let n = 12 (binary 1100).
  • n - 1 = 11 (binary 1011).
  • n & (n - 1) is 1100 & 1011 = 1000 (which is 8). The rightmost '1' has been cleared.
  • The loop runs as many times as there are set bits.

The Code:

#![allow(unused)]
fn main() {
fn hamming_weight_kernighan(mut n: u32) -> i32 {
    let mut count = 0;
    while n != 0 {
        // This clears the least significant bit
        n = n & (n - 1);
        count += 1;
    }
    count
}
}

Why it's better: The number of loop iterations is equal to the number of set bits. This is much faster for "sparse" numbers (numbers with few '1's). For the worst case (0xFFFFFFFF), it performs 32 iterations, but on average, it's much faster.


2. Lookup Table (LUT)

This method trades memory for speed. We can pre-calculate the Hamming weight for every possible 8-bit number (a byte) and store it in an array. Then, we can process a 32-bit integer as four separate 8-bit chunks.

The Code:

#![allow(unused)]
fn main() {
// Pre-generate this table once
const BITS_IN_BYTE: [i32; 256] = {
    let mut table = [0; 256];
    let mut i = 0;
    while i < 256 {
        // Using the Kernighan algorithm to generate the table entries
        let mut n = i;
        let mut count = 0;
        while n > 0 {
            n &= n - 1;
            count += 1;
        }
        table[i] = count;
        i += 1;
    }
    table
};

fn hamming_weight_lut(n: u32) -> i32 {
    // Break the 32-bit integer into four 8-bit bytes and sum their weights
    BITS_IN_BYTE[(n & 0xff) as usize] +
    BITS_IN_BYTE[((n >> 8) & 0xff) as usize] +
    BITS_IN_BYTE[((n >> 16) & 0xff) as usize] +
    BITS_IN_BYTE[((n >> 24) & 0xff) as usize]
}
}

Why it's better: This is extremely fast. It has no loops or branches, just a few bitwise operations, four array lookups, and three additions. Its performance is constant regardless of the input. The main downside is the memory cost of the lookup table (256 bytes in this case).


3. Parallel Bit-Counting (SWAR)

This is a "bit-twiddling hack" that computes the Hamming weight in parallel. It works by treating the 32-bit integer as a vector of smaller fields and adding them up simultaneously (SWAR stands for "SIMD Within A Register").

How it works (conceptual):

  1. Count set bits in adjacent 2-bit chunks.
  2. Sum the results into 4-bit chunks.
  3. Sum the results into 8-bit chunks.
  4. Sum the results into 16-bit chunks.
  5. Sum the final results into a 32-bit chunk.

The "magic numbers" are masks used to prevent the sums from overflowing into the next chunk.

The Code:

#![allow(unused)]
fn main() {
fn hamming_weight_parallel(mut n: u32) -> i32 {
    // Step 1: Count bits in 2-bit chunks (result in each chunk is 0, 1, or 2)
    // 0x55555555 is 01010101...
    n = (n & 0x55555555) + ((n >> 1) & 0x55555555);

    // Step 2: Sum 2-bit chunk results into 4-bit chunks (max result 4)
    // 0x33333333 is 00110011...
    n = (n & 0x33333333) + ((n >> 2) & 0x33333333);

    // Step 3: Sum 4-bit chunk results into 8-bit chunks (max result 8)
    // 0x0F0F0F0F is 00001111...
    n = (n & 0x0F0F0F0F) + ((n >> 4) & 0x0F0F0F0F);

    // Step 4: Sum 8-bit chunk results into 16-bit chunks (max result 16)
    // 0x00FF00FF is 0000000011111111...
    n = (n & 0x00FF00FF) + ((n >> 8) & 0x00FF00FF);

    // Step 5: Sum 16-bit chunk results into a 32-bit chunk (max result 32)
    // 0x0000FFFF is 00000000000000001111111111111111
    n = (n & 0x0000FFFF) + ((n >> 16) & 0x0000FFFF);

    n as i32
}
}

Why it's better: Like the lookup table, this is a branchless, loop-free algorithm with constant-time performance. It uses no extra memory. This is often how standard library implementations of count_ones() are written for architectures that lack a dedicated hardware instruction.


Conclusion: Why n.count_ones() is the Actual Best Solution

You are right to be aware of n.count_ones(). For any real-world code, it is the superior choice for three key reasons:

  1. Hardware Intrinsics: Most modern CPUs (like x86 and ARM) have a single, highly-optimized machine instruction to count set bits (e.g., POPCNT, VCNT). The Rust compiler is smart enough to translate n.count_ones() directly into that single instruction. None of the algorithms above can beat a dedicated hardware instruction that runs in 1-3 clock cycles.

  2. Optimal Fallback: On the rare occasion that the target CPU doesn't have a POPCNT instruction, the Rust standard library will use a heavily optimized fallback, typically a variation of the parallel (SWAR) or lookup table method. You get the best possible implementation for your target architecture automatically.

  3. Readability and Maintainability: Code should be as clear as possible. n.count_ones() perfectly describes its intent. The other algorithms, while clever, are harder to read and understand at a glance.

Summary Table

MethodPerformanceIterations / ComplexityMemory UsageBest Use Case
Simple IterationSlow32 (Fixed)NoneSimple to understand, educational.
Brian Kernighan'sGood (Variable)k (where k is # of set bits)NoneGreat for sparse inputs; good interview question.
Lookup Table (LUT)Very FastConstant (O(1))~256 bytesEmbedded systems or scenarios where memory is cheap and speed is critical.
Parallel (SWAR)Very FastConstant (O(1))NoneWhen a hardware instruction is unavailable and you can't use extra memory.
n.count_ones()Optimal1 CPU instructionNoneAlmost always. Production code in Rust.

Optimizing a Rust Substitution Cipher Implementation

The Question

I have the following Rust code that implements a substitution cipher. The key string is used to build a substitution map, and then the message is decoded using that map. Can this code be made better?

Original Code

#![allow(unused)]
fn main() {
use std::collections::HashMap;

fn decode(key: String, message: String) -> String {
    let mut map: HashMap<char, char> = HashMap::new();
    map.insert(' ', ' ');
    let mut mapped_c = 'a';
    for ch in key.chars() {
        if ch != ' ' && !map.contains_key(&ch) {
            map.insert(ch, mapped_c);
            mapped_c = ((mapped_c as u8) + 1) as char;
        }
    }
    let mut result = String::new();
    for ch in message.chars() {
        if let Some(ch_mapped) = map.get(&ch) {
            result.push(*ch_mapped);
        }
    }
    result
}
}

The Answer

Excellent question. Yes, this code can definitely be improved in terms of performance, readability, and idiomatic Rust.

Your current code is clear and correctly implements a substitution cipher based on the first appearance of characters in a key. However, it has a few areas for optimization.

Let's break down the improvements.

1. Idiomatic Rust & Readability Improvements

Use the entry API

Instead of checking !map.contains_key(&ch) and then inserting, you can use the entry API. This is more efficient as it only performs one lookup in the map, and it's considered more idiomatic.

#![allow(unused)]
fn main() {
// Your original code
if ch != ' ' && !map.contains_key(&ch) {
    map.insert(ch, mapped_c);
    mapped_c = ((mapped_c as u8) + 1) as char;
}

// Using the entry API
use std::collections::hash_map::Entry;

if ch != ' ' {
    if let Entry::Vacant(v) = map.entry(ch) {
        v.insert(mapped_c);
        mapped_c = ((mapped_c as u8) + 1) as char;
    }
}
}

This ensures the logic for checking and inserting is an atomic operation and is generally cleaner.

2. Performance Improvements

Pre-allocating the Result String

You are building the result string by pushing one character at a time. Each time the string's capacity is exceeded, Rust has to allocate a new, larger block of memory and copy the old content over. You can avoid this by pre-allocating the string with the right capacity.

#![allow(unused)]
fn main() {
// Before
let mut result = String::new();

// After: Guarantees only one memory allocation for the string
let mut result = String::with_capacity(message.len());
}

Using an Array as a Lookup Table (Major Improvement)

A HashMap is a powerful, general-purpose tool. However, when your keys are chars (especially if you can assume they are ASCII), using an array as a direct lookup table is significantly faster.

  • Why? Accessing an array element by its index (map[i]) is a direct memory lookup (O(1) with a very small constant factor). A HashMap lookup involves hashing the key, finding the right bucket, and potentially checking for collisions (average O(1) but with a much larger constant factor).

Let's assume the characters are within the ASCII range (0-127). We can create an array of size 128 to store the mappings.

The Refactored Solution

This version incorporates the performance improvements. It's much faster for typical inputs because it avoids all hashing and uses a simple array lookup.

#![allow(unused)]
fn main() {
fn decode_message(key: &str, message: &str) -> String {
    // 1. Use an array as a faster lookup table for ASCII characters.
    // Initialize with a sentinel value (0) to indicate "not mapped yet".
    let mut map = [0u8; 128];

    // Map space to itself.
    map[b' ' as usize] = b' ';

    // 2. Use `b'a'` for byte literals, which is slightly more efficient.
    let mut current_char = b'a';

    // 3. Build the mapping table.
    for &byte in key.as_bytes() {
        // We only care about characters that haven't been mapped yet.
        if byte != b' ' && map[byte as usize] == 0 {
            map[byte as usize] = current_char;
            current_char += 1;
        }
    }

    // 4. Pre-allocate the result string for a single allocation.
    let mut result = String::with_capacity(message.len());

    // 5. Decode the message using the fast array lookup.
    for &byte in message.as_bytes() {
        // The map contains the substitution if it was in the key, or 0 otherwise.
        // The original code skipped characters not in the map, so we do the same.
        let mapped_char = map[byte as usize];
        if mapped_char != 0 {
             result.push(mapped_char as char);
        }
    }

    result
}
}

Summary of Improvements

AspectOriginal HashMap ApproachImproved Array ApproachWhy it's Better
SpeedModerateVery FastArray indexing is much faster than hashing and hash table lookups. Working with bytes (u8) avoids Unicode overhead.
MemoryHashMap overheadMinimal ([u8; 128] is 128 bytes)Lower memory footprint and better cache locality.
GeneralityHandles any charAssumes ASCIIThe array approach is less general but is a perfect fit for problems constrained to ASCII or byte-sized characters.
ReadabilityClearMore complexThe HashMap version is arguably easier for a beginner to read, but the array version is a standard, high-performance pattern.

For most competitive programming and performance-critical scenarios involving character substitution, the array-based lookup table is the superior solution.


This chapter includes my notes on Neetcode

Static Arrays

  • The biggest limitation of static arrays is their size.
  • In JS or Python you usually do not have this issue since by default their array is not static array. Instead they use dynamic arrays!
  • You cannot de-allocate a static value meaning shrink its size

Dynamic Arrays

  • When you initialize it, there might be a default size for it! For example the default size of ArrayList is 10!
  • When using Dynamic Arrays, when you run out of memory you need to double the size of the current array. The amortized time complexity is proved to be .
  • Basically time complexity of dynamic array is identical to static array
    • Note that although the complexity is the same, static arrays are more efficient.

Stacks

  • Can be created using dunamci array

Linked-Lists

  • Usually we have a tail and head pointer.
    • Adding a node to the end is
    • Assuming you have the pointer to the previous of a target node, removing it is and this is one the benefit of Liked-List versus an Array.
  • However, practically speaking, removing a node is .
  • Traverse a list:
  ListNode cur = ListNode1;
  while (cur != null) {
    cur = cur.Next;
  }

Doubly-Linked-List

  • You will have head and tail.
  • Add/Remove to/from the end of the list is

Note: You can implement Stack using Arrays as well as Linked-List. However, it is more common to use arrays because as we mentioned before using a dynamic array you can not only easily push and pop from the end of the array, but also you'd have access to each element as well.

Queue

  • We need for insertion into the add of the queue and delete from the beginning of it.
  • We cannot accomplish this using Arrays since removing from the beginning of the array is
  • Linked-List is a good candidate:
    • There is a head and there is a tail.
  • You can implement Queues with Arrays. But, it will be a lot more complicated.

Recursion

  • The best way to represent recursion is decision tree!

  • For Fibonacci example: and and

int factorial(int n) {
  if (n <= 1) {
    return 1;
  }
  return factorial(n-1)*n;
}
  • This solution is time complexity and also memory complexity.

Sorts

Insertion Sort

void InsertionSort(int[] nums) {
  for (int i=1; i < nums.Length; i++) {
    j = i;
    while (j>0 && nums[j] < nums[j-1]) {
      int tmp = nums[j];
      nums[j] = nums[j-1];
      nums[j-1] = tmp;
      j--;
    }
  }
}
  • Best case is when the array is already sorted:
  • Worst case is then the array is sorted in reverse order:
  • The algorithm is stable
  • The algorithm is in-place

Merge Sort

  • We divide into maximum stages
  • For each stage we ned to merge all sub-arrays
  • We can make it stable:
    • When merging sub-arrays, if the left sub-array's element is less or equal to to the right sub-array's element, it takes priority to be moved to the main array.
  • The algorithm is NOT in-place.

Quick Sort

  • First we partition the array taking the last element as the pivot
    • Use two pointers
  • Quick Sort both partitions
public int[] QuickSorting(int[] arr, int s, int e)
{
  if (e - s + 1 <= 1)
  {
    return arr;
  }

  int pivot = arr[e];
  int left = s;       // pointer for left side

  // Partition: elements smaller than pivot on left side
  for (int i = s; i < e; i++)
  {
    if (arr[i] < pivot)
    {
      int tmp = arr[left];
      arr[left] = arr[i];
      arr[i] = tmp;
      left++;
    }
  }

  // Move pivot in-between left & right sides
  arr[e] = arr[left];
  arr[left] = pivot;

  // Quick sort left side
  QuickSorting(arr, s, left - 1);

  // Quick sort right side
  QuickSorting(arr, left + 1, e);

  return arr;
}
  • Worst case: when the array was already sorted!
  • It is in-place and does not require any extra memory!
  • It is not stable! It might be modified to make it stable!
  • On average it is

Bucket Sorat

  • Required memory is range of possible values
  • It is not stable
    • You can make it stable!

Trees

Binary Search Tree (BST)

  • They generally do not contain duplicate values
  • If the tree is balanced, search is
    • If it is not balanced, worst case scenario is
    • Technically it will be where h represents the height of the tree
bool Search(RootNode root, int target) {
  if (root == null) {
    return false;
  }
  if (target > root.val)
    return Search(root.right, target);
  if (target < root.val)
    return Search(root.left, target);
  return true;
}

IMPORTANT: Why do we need this considering you can use a sorted array?

  • Because with a sorted array, operations like insert/remove values to the array will be .
  • For BST, insert/remove is as well.

Insert into BST

Node insert(Node root, int value) {
  if (root == null) {
    return new Node(value);
  }

  if (value > root.val) {
    root.right = insert(root.right, val);
  } else if (value < root.val) {
    root.left = insert(root.left, val);
  }
  return root;
}

This way of inserting data into a BST will end up with unbalanced tree. There are data structures like AVL Trees that resolve this issue.

Remove from BST

// Return the minimum value node of the BST.
public TreeNode MinValueNode(TreeNode root) {
  TreeNode curr = root;
  while (curr != null && curr.Left != null) {
    curr = curr.Left;
  }
  return curr;
}

// Remove a node and return the root of the BST.
public TreeNode Remove(TreeNode root, int val) {
  if (root == null) {
    return null;
  }
  if (val > root.Value) {
    root.Right = Remove(root.Right, val);
  } else if (val < root.Value) {
    root.Left = Remove(root.Left, val);
  } else {
    if (root.Left == null) {
      return root.Right;
    } else if (root.Right == null) {
      return root.Left;
    } else {
      TreeNode minNode = MinValueNode(root.Right);
      root.Value = minNode.Value; 
      root.Right = Remove(root.Right, minNode.Value);
    }
  }
  return root;
}

BST Traversal

DFS

In-Order
void inorder(Node root) {
  if (root == null)
    return;
  inorder(root.left);
  print(root);
  inorder(root.right); 
}

Note: If you were given some random values, you could sort them using BST. Now you have to insert all the values into BST which for a balanced tree will be and then traversing it will be . The sum of the two will be .

Note: All preorder, postorder and inorder traversals are Depth First Search examples.

Pre-Order
void preorder(Node root) {
  if (root == null) {
    return;
  }
  print(root.val);
  preorder(root.left);
  preorder(root.right);
}
Post-Order
void postorder(Node root) {
  if (root == null) {
    return;
  }
  postorder(root.left);
  postorder(root.right);
  print(root.val);
}
  void BFS(Node node)
  {
    Queue<Node> queue = new();

    int level = 0;
    while (queue.Count > 0)
    {
      Console.WriteLine($"Level = {level}");
      for (int i = 0; i < queue.Count; i++)
      {
        Node cur = queue.Dequeue();
        Console.WriteLine(cur.val);
        if (cur.left != null)
        {
          queue.Enqueue(cur.left);
        }
        if (cur.right != null)
        {
          queue.Enqueue(cur.right);
        }
      }
      level++;
    }
  }

Sets and Maps

  • One implementation of Sets and Maps could be a BST!
  • If you use BST (since BST has unique values) to implement a set, insert and remove is versus if you use arrays.

Backtracking

Question: Determine if a path exists from the root of the tree to a leaf node. It may not contain any zeroes.

bool FindPath(Node root) {
  if (root != null || root.val == 0) {
    return false;
  }
  if (root.left != null && root.right != null) {
    return true;
  }
  if (FindPath(root.left), val) {
    return true;
  }
  if (FindPath(root.left), val) {
    return true;
  }
  return false;
}

Now we will make it a bit more complicated. At the end if there is path, we need to print the path.

bool FindPath(Node root, Stack<int> path) {
  if (root != null || root.val == 0) {
    return false;
  }
  path.Push(root.val);
  if (root.left != null && root.right != null) {
    return true;
  }
  if (FindPath(root.left), val) {
    return true;
  }
  if (FindPath(root.left), val) {
    return true;
  }
  path.Pop();
  return false;
}

Heap/Priority Queue

  • The purpose of using this is to find the minimum value in .
  • Duplicate values can exist in the structure
  • Usually min Heap is used
  • The functionality is priority queue however under the hood it uses the heap data structure.
  • It has two properties:
    • It is a complete binary tree: every single level is gonna be completely full except the last level
  • IMPORTANT: It uses array under the hood.
    • Queue to LinkedList is like PriorityQueue to Heap (particularly binary heap)
  • Index 0 of array is not used
class Heap {
  private List<int> _heap;
  public Heap() {
    heap = new (){0};
  }
}

Insert into heap

push(val) {
  _heap.Add(val);
  int i = _heap.Length - 1;

  // Percolate up
  while _heap[i] < _heap[i/2] {
    tmp = _heap[i];
    _heap[i] = heap[i/2];
    heap[i/2] = tmp;
    i /= 2;
  }
}
  • The operation is

Removing from a heap

We swap the first value with the last value. Then starting from root we will go down and swap with a child until both child are smaller than it.

int pop() {
  if (heap.Count == 1)
  {
    // return null;
  }
  if (heap.Count == 2)
  {
    int res = heap[heap.Count - 1];
    heap.Remove(heap.Count - 1);
    return res; // equivalent to heap.remove(1)
  }

  int res = heap[1];
  // Move last value to root
  heap[1] = heap[heap.Count - 1];
  heap.Remove(heap.Count - 1);
  int i = 1;
  // Percolate down
  while (2 * i < heap.Count)
  {
    if (2 * i + 1 < heap.Count &&
    heap[2 * i + 1] < heap[2 * i] &&
    heap[i] > heap[2 * i + 1])
    {
      // Swap right child
      int tmp = heap[i];
      heap[i] = heap[2 * i + 1];
      heap[2 * i + 1] = tmp;
      i = 2 * i + 1;
    }
    else if (heap[i] > heap[2 * i])
    {
      // Swap left child
      int tmp = heap[i];
      heap[i] = heap[2 * i];
      heap[2 * i] = tmp;
      i = 2 * i;
    }
    else
    {
      break;
    }
  }
  return res;
}
  • This operation is also
Advantages of Heap over BST:
  • Finding min/max is vs
  • You can build a heap (by an array) with (proof will be given below)

Heapify

  • You will be given an array
  • Push the first value into the end of the array
  • Now from the end we will make sure every true is a heap.
    • Therefore half of the tree (leaves) will be already a heap
    • The first index we really need to heapify is the index
  • Now you need to percolate down now and repeat it for all the nodes before.
  • You can use heapify and then popping from the queue for times and sort an array:
public void Heapify(List<int> arr)
{
  // 0-th position is moved to the end
  arr.Add(arr[0]);

  heap = arr;
  int cur = (heap.Count - 1) / 2;
  while (cur > 0)
  {
    // Percolate Down
    int i = cur;
    while (2 * i < heap.Count)
    {
      if (2 * i + 1 < heap.Count &&
      heap[2 * i + 1] < heap[2 * i] &&
      heap[i] > heap[2 * i + 1])
      {
        // Swap right child
        int tmp = heap[i];
        heap[i] = heap[2 * i + 1];
        heap[2 * i + 1] = tmp;
        i = 2 * i + 1;
      }
      else if (heap[i] > heap[2 * i])
      {
        // Swap left child
        int tmp = heap[i];
        heap[i] = heap[2 * i];
        heap[2 * i] = tmp;
        i = 2 * i;
      }
      else
      {
        break;
      }
    }
    cur--;
  }
  return;
}

Heap is not suitable for search. They are NOT intended for that.


Hash Maps

TreeMap (It is ordered)HashMapOperation
Insert
Remove
Search
Inorder
  • Actually worst case time complexity of operations Insert, Remove and Search is not but .
  • Hash map are not sorted usually!
  • Hashmap under the hood is an array!
  • Think about:
    • Hashing (something like using prime numbers)
    • Collision: it will happen regardless of the hashing algorithm
    • Rehashing: when the size of the hashmap reaches half of the capacity
      • we need to move every element based on the rehashing
    • Readdressing

public class Pair
{
  public string Key { get; set; }
  public string Val { get; set; }

  public Pair(string key, string val)
  {
    this.Key = key;
    this.Val = val;
  }
}

public class HashMap
{
  int Size { get; set; }
  int Capacity { get; set; }
  Pair[] Map { get; set; }

  public HashMap()
  {
    Size = 0;
    Capacity = 2;
    Map = new Pair[2];
  }

  public int Hash(string key)
  {
    int index = 0;
    for (int i = 0; i < key.Length; i++)
    {
      index += (int)key[i];
    }
    return index % this.Capacity;
  }

  public string Get(string key)
  {
    int index = this.Hash(key);
    while (this.Map[index] != null)
    {
      if (this.Map[index].Key == key)
      {
        return this.Map[index].Val;
      }
      index += 1;
      index %= this.Capacity;
    }
    return string.Empty;
  }

  public void Put(string key, string val)
  {
    int index = this.Hash(key);

    while (true)
    {
      if (this.Map[index] == null)
      {
        this.Map[index] = new Pair(key, val);
        this.Size += 1;
        if (this.Size >= this.Capacity / 2)
        {
          this.ReHash();
        }
        return;
      }
      else if (this.Map[index].Key == key)
      {
        this.Map[index].Val = val;
        return;
      }
      index += 1;
      index %= this.Capacity;
    }
  }

  public void Remove(string key)
  {
    if (this.Get(key) == null)
    {
      return;
    }

    int index = this.Hash(key);
    while (true)
    {
      if (this.Map[index].Key == key)
      {
        // Removing an element using open-addressing actually causes a bug,
        // because we may create a hole in the list, and our get() may
        // stop searching early when it reaches this hole.
        this.Map[index] = null;
        this.Size -= 1;
        return;
      }
      index += 1;
      index %= this.Capacity;
    }
  }

  public void ReHash()
  {
    this.Capacity = 2 * this.Capacity;
    Pair[] newMap = new Pair[this.Capacity];

    Pair[] oldMap = this.Map;
    this.Map = newMap;
    this.Size = 0;
    foreach (Pair p in oldMap)
    {
      if (p != null)
      {
        this.Put(p.Key, p.Val);
      }
    }
  }
}

Graphs

  • Vertex is equivalent to node
  • Three ways to represent them:
    • Matrix
    • Adjacency matrix
    • Adjacency list
  • It's most common to use adjacency list for graph representation.
  • The second one is usually rare since it takes much more space.

Adjacency Matrix: In the matrix below, every 1 represent a path from Node #row to Node #col.

1111
0110
0100
1111

Adjacency List: Every node has a list of neighbors:

class GraphNode {
  int val;
  List<GraphNode> neighbors;
}

Matrix DFS

Question: Count the unique paths from the top left to the bottom right. A single path may only move along 0's and can't visit the same cell more than once.

Note: Ask your interviewer there is gonna be at least one path from the source to the destination.

int Dfs(int[][] grid, int r, int c, int[][] visit)
{
  int ROWS = grid.Length, COLS = grid[0].Length;

  if (Math.Min(r, c) < 0 || r == ROWS || c == COLS ||
      visit[r][c] == 1 || grid[r][c] == 1)
  {
    return 0;
  }
  if (r == ROWS - 1 && c == COLS - 1)
  {
    return 1;
  }
  visit[r][c] = 1;

  int count = 0;
  count += Dfs(grid, r + 1, c, visit);
  count += Dfs(grid, r - 1, c, visit);
  count += Dfs(grid, r, c + 1, visit);
  count += Dfs(grid, r, c - 1, visit);

  visit[r][c] = 0;
  return count;
}

  • Memory Complexity:
  • Time Complexity:

Matrix BFS

Question: Find the length of the shortest path from the top left of the grid to them bottom right.

// Shortest path from top left to bottom right
public int BFS(int[][] grid)
{
  int nr = grid.Length; int nc = grid[0].Length;
  Queue<(int row, int col)> q = new Queue();
  q.Enqueue((0, 0));
  int length = 1;
  while (q.Any())
  {
    int size = q.Count();
    for (int i = 0; i < size; i++)
    {
      (int row, int col) = q.Dequeue();
      if (row < 0 || row >= nr || col < 0 || col >= nc || grid[row][col] == 1)
      {
        continue;
      }
      if (row == nr - 1 && col == nc - 1)
      {
        return length;
      }
      grid[row][col] = 1;

      q.Enqueue((row - 1, col));
      q.Enqueue((row, col + 1));
      q.Enqueue((row + 1, col));
      q.Enqueue((row, col - 1));
    }
    length++;
  }
  return -1; // This should never be called
}
  • Note: BFS is much more efficient than DFS.
  • Time Complexity is

Adjacency List

Question: Count the unique paths from the top left to the bottom right. A single path may only move along 0's and can't visit the same cell more than once.

// Count paths (backtracking)
public int DFS(String node, String target, Dictionary<String, List<String>> adjList, HashSet<String> visit)
{
  if (visit.Contains(node))
  {
    return 0;
  }
  if (node == target)
  {
    return 1;
  }
  int count = 0;
  visit = new HashSet<String>
  {
      node
  };
  foreach (String neighbor in adjList[node])
  {
    count += DFS(neighbor, target, adjList, visit);
  }
  visit.Remove(node);
  return count;
}
  • Like every backtracking algorithm this is exponential:

Question: Find the length of the shortest path from the top left of the grid to them bottom right.

// Shortest path from node to target.
public int BFS(String node, String target, Dictionary<String, List<String>> adjList)
{
  int length = 0;
  HashSet<String> visit = new HashSet<String>();
  Queue<String> q = new Queue<string>();
  visit.Add(node);
  q.Enqueue(node);

  while (q.Count != 0)
  {
    int queueLength = q.Count;
    for (int i = 0; i < queueLength; i++)
    {
      String curr = q.Peek();
      q.Dequeue();
      if (curr.Equals(target))
      {
        return length;
      }
      foreach (String neighbor in adjList[curr])
      {
        if (!visit.Contains(neighbor))
        {
          visit.Add(neighbor);
          q.Enqueue(neighbor);
        }
      }
    }
    length++;
  }
  return length;
}
  • Time Complexity
  • Space Complexity since we need to add every vertices into the hashmap and to the queue.

Dynamic Programming

1d Dynamic Programming

Previously we solved the Fibonacci series problem. However, it was a bruteForce solution:

// Fibonacci-> Brute Force
public static int BruteForce(int n)
{
  if (n <= 1)
  {
    return n;
  }
  return BruteForce(n - 1) + BruteForce(n - 2);
}

If you add Memoization to this, you can make it much better:

// Memoization
public static int Memoization(int n, int[] cache)
{
  if (n <= 1)
  {
    return n;
  }
  if (cache[n] != 0)
  {
    return cache[n];
  }
  cache[n] = Memoization(n - 1, cache) + Memoization(n - 2, cache);
  return cache[n];
}
  • Time complexity
  • This implementation of memorization is TOP-DOWN and also recursive.
  • Some people do not consider this implementation as dynamic programming.
  • True Dynamic Programming:
    • It is bottom up
// Dynamic Programming
public static int Dp(int n)
{
  if (n < 2)
  {
    return n;
  }

  int[] dp = { 0, 1 };
  int i = 2;
  while (i <= n)
  {
    int tmp = dp[1];
    dp[1] = dp[0] + dp[1];
    dp[0] = tmp;
    i++;
  }
  return dp[1];
}
  • This solution is of time complexity and with O(1) memory.

2-d Dynamic Programming

Question: Count the number of the path from source top-left of a matrix to the bottom-right. You are only allowed to move down or right.

// Brute Force - Time: O(2 ^ (n + m)), Space: O(n + m)
public static int BruteForce(int r, int c, int rows, int cols)
{
  if (r == rows || c == cols)
  {
    return 0;
  }
  
  if (r == rows - 1 && c == cols - 1)
  {
    return 1;
  }

  return (BruteForce(r + 1, c, rows, cols) +
  BruteForce(r, c + 1, rows, cols));
}

Now we can use a memoization solution:

// Memoization - Time and Space: O(n * m)
public static int Memoization(int r, int c, int rows, int cols, int[][] cache)
{
  if (r == rows || c == cols)
  {
    return 0;
  }
  if (cache[r][c] > 0)
  {
    return cache[r][c];
  }
  if (r == rows - 1 && c == cols - 1)
  {
    return 1;
  }
  cache[r][c] = (Memoization(r + 1, c, rows, cols, cache) +
    Memoization(r, c + 1, rows, cols, cache));
  return cache[r][c];
}

With Dynamic Programming:

// Dynamic Programming - Time: O(n * m), Space: O(m), where m is num of cols
public static int Dp(int rows, int cols)
{
  int[] prevRow = new int[cols];

  for (int i = rows - 1; i >= 0; i--)
  {
    int[] curRow = new int[cols];
    curRow[cols - 1] = 1;
    for (int j = cols - 2; j >= 0; j--)
    {
      curRow[j] = curRow[j + 1] + prevRow[j];
    }
    prevRow = curRow;
  }
  return prevRow[0];
}

Kadane's Algorithm

Question: Find a non-empty subarray with the largest sum

public static int BruteForce(int[] nums)
{
  if (nums == null || nums.Length == 0)
  {
    return int.MinValue;
  }
  int maxSum = nums[0];

  for (int i = 0; i < nums.Length; i++)
  {
    int curSum = 0;
    for (int j = i; j < nums.Length; j++)
    {
      curSum += nums[j];
      maxSum = Math.Max(maxSum, curSum);
    }
  }
  return maxSum;
}
public static int Kadanes(int[] nums)
{
  if (nums == null || nums.Length == 0)
  {
    return int.MinValue;
  }
  int maxSum = nums[0];
  int curSum = 0;

  for (int i = 0; i < nums.Length; i++)
  {
    curSum = Math.Max(curSum, 0);
    curSum += nums[i];
    maxSum = Math.Max(maxSum, curSum);
  }
  return maxSum;
}
public static int[] SlidingWindow(int[] nums)
{
  int resultR = -1;
  int resultL = -1;

  if (nums == null || nums.Length == 0)
  {
    return new int[] { resultL, resultR };
  }
  int L = 0;
  int curSum = 0;
  int curMax = nums[0];

  for (int R = 0; R < nums.Length; R++)
  {
    curSum += nums[R];
    if (curSum < 0)
    {
      L = R+1;
      curSum = 0;
      continue;
    }
    if (curSum >= curMax)
    {
      resultL = L;
      resultR = R;
    }
  }
  return new int[] { resultL, resultR };
}

Sliding Windows Fixed:

Q: Given an array, return true if there are two elements within a window of size k that are equal.

public static bool CloseDuplicates(int[] nums, int k) {
    HashSet<int> window = new HashSet<int>(); // Cur window of size <= k
    int L = 0;

    for (int R = 0; R < nums.Length; R++) {
        if (R - L + 1 > k) {
            window.Remove(nums[L]);
            L++;
        }
        if (window.Contains(nums[R])) {
            return true;
        }
        window.Add(nums[R]);
    }
    return false;
}

Sliding Windows - Variable Size

Question: Q: Find the length of the longest subarray, with the same value in each position.

public static int ShortestSubarray(int[] nums, int target) {
    int L = 0, total = 0;
    int length = int.MaxValue;

    for (int R = 0; R < nums.Length; R++) {
        total += nums[R];
        while (total >= target) {
            length = Math.Min(R - L + 1, length);
            total -= nums[L];
            L++;
        }
    }

    if (length ==  int.MaxValue) {
        return 0;
    } 
    return length;
}

Two Pointers

Question: Check if an array is palindrome.

public static bool IsPalindrome(string word) {
  int L = 0;
  int R = word.Length-1;

  while (L <= R) {
    if (word[L] != word[R]) {
      return false;
    }
    L++;
    R--;
  }
  return true;
}

Question: Given a sorted input array, return the two indices of two elements which sums up to the target value. Assume there's exactly one solution.

public static int[] TargetSum(int[] nums, int target) {
  int L = 0;
  int R = nums.Length-1;
  int sum;
  while (L <= R) {
    sum = nums[L] + nums[R];
    if (sum > target) {
      R--;
    } else if (sum < target) {
      L++;
    } else {
      return new int[2]{L,R};
    }
  }
  return null;
}

Prefix Sum

Question: Given an array of values, design a data structure that can query the sum of a sub-array of the values.

public class PrefixSum {
  List<int> prefix;

  public PrefixSum(int[] nums) {
    prefix = new();
    sum = 0;
    foreach (var num in nums) {
      sum += num;
      prefix.Add(sum);
    }
  }

  public int RangeSum(int left, int right) {
    return prefix[right] - prefix[left > 0 ? left-1 : 0];
  }
}

Fast and Slow Pointers

Question: Find the middle of a linked list.

public static ListNode middleOfList(ListNode head) {
  ListNode slow = head, fast = head;
  while (fast != null && fast.next != null) {
    slow = slow.next;
    fast = fast.next.next;
  }
  return slow;
}

Question: Determine if a Linked List has a cycle.

public static bool HasCycle(ListNode head) {
  HashSet<ListNode> visited = new HashSet<ListNode>();
  while (head != null) {
    if (visited.Contains(head)) {
      return true; // Cycle found
    }
    visited.Add(head);
    head = head.next;
}
  return false; // No cycle
}

The solution above has an O(n) space complexity. Therefore, using two pointers we attempt to improve it:

public static bool hasCycle(ListNode head) {
  ListNode slow = head, fast = head;
  while (fast != null && fast.next != null) {
    slow = slow.next;
    fast = fast.next.next;
    if (slow == fast) {
      return true;
    }
  }
  return false;
}

Question: Determine if a Linked List has a cycle and return the head.

public static ListNode cycleStart(ListNode head) {
  ListNode slow = head, fast = head;
  while (fast != null && fast.next != null) {
    slow = slow.next;
    fast = fast.next.next;
    if (slow == fast) {
        break;
    }
  }
  if (fast == null || fast.next == null) {
    return null;
  }
  ListNode slow2 = head;
  while (slow != slow2) {
    slow = slow.next;
    slow2 = slow2.next;
  }
  return slow;
}

Trie (Prefix Tree)

The goal of a trie is to insert words (string of characters) in constant time and search of words in . So far a hashset can do the trick. However, it cannot provide search prefix in .

Note: One application for this data structure is for search engines and their auto completion functionalities.

class TrieNode {
    public bool word;   // isLeaf
    public Dictionary<char, TrieNode> children = new Dictionary<char, TrieNode>();
}

public class Trie {
  TrieNode root;

  public Trie() {
    root = new TrieNode(); 
  }
}

public void insert(string word) {
  TrieNode curr = this.root;
  foreach (char c in word) {
    if (!curr.children.ContainsKey(c)) {
      curr.children[c] = new TrieNode();
    }
    curr = curr.children[c];
  }
  curr.word = true;
}

public bool search(string word) {
  TrieNode curr = this.root;
  foreach (char c in word) {
    if (!curr.children.ContainsKey(c)) {
      return false;
    }
    curr = curr.children[c];
  }
  return curr.word;
}


public bool startsWith(string prefix) {
  TrieNode curr = this.root;
  foreach (char c in prefix) {
    if (!curr.children.ContainsKey(c)) {
      return false;
    }
    curr = curr.children[c];
  }
  return true;
}

Union Find

Union-Find is a useful tool for keeping track of nodes connected in a graph and detecting cycles in a graph. Of course, we can achieve this with DFS as well by using a hashset, call it, seen. However, DFS is a good choice when there is a static graph, i.e. no edges are added overtime. If we are adding edges overtime, that makes the graph dynamic, and Union-Find is a better choice.

public class UnionFind {
    
  Dictionary<int, int> par;
  Dictionary<int, int> rank;

  public UnionFind(int n) {
    par = new Dictionary<int, int>();
    rank = new Dictionary<int, int>();

    for (int i = 1; i < n + 1; i++) {
      par[i] = i;
      rank[i] = 0;
    }
  }

  // Find parent of n, with path compression.
  public int find(int n) {
    int p = par[n];
    while (p != par[p]) {
      par[p] = par[par[p]];
      p = par[p];
    }
    return p;
  }

  // Union by height / rank.
  // Return false if already connected, true otherwise.
  public bool union(int n1, int n2) {
    int p1 = this.find(n1), p2 = this.find(n2);
    if (p1 == p2) {
      return false;
    }

    if (rank[p1] > rank[p2]) {
      par[p2] = p1;
    } else if (rank[p1] < rank[p2]) {
      par[p1] = p2;
    } else {
      par[p1] = p2;
      rank[p2] = rank[p2] + 1;
    }
    return true;
  }
}

Segment Tree

Application: Let's say you have a list of index and an value and need to dynamically perform two operations:

  • update(index, value)
  • querySum(leftIndex, rightIndex)

With a prefix array and a regular array you can perform update in and then when required perform querySum in .

Segment Tree helps to perform both of in .

public class SegmentTree {
  int sum;
  SegmentTree left;
  SegmentTree right;
  int L;
  int R; 

  public SegmentTree(int total, int L , int R) {
    this.sum = total;
    this.left = null;
    this.right = null;
    this.L = L;
    this.R = R;
  }

  public static SegmentTree build(int[] nums, int L, int R) {
    if (L == R) {
      return new SegmentTree(nums[L], L, R);
    }

    int M = (L + R) / 2;
    SegmentTree root = new SegmentTree(0, L, R);
    root.left = SegmentTree.build(nums, L, M);
    root.right =  SegmentTree.build(nums, M + 1, R);
    root.sum = root.left.sum + root.right.sum;
    return root;
  }

  // O(logn)
  public void update(int index, int val) {
    if (this.L == this.R) {
      this.sum = val;
      return;
    }

    int M = (this.L + this.R) / 2;
    if (index > M) {
      this.right.update(index, val);
    } else {
      this.left.update(index, val);
    }
    this.sum = this.left.sum + this.right.sum;
  }

  // O(logn)
  public int rangeQuery(int L, int R) {
    if (L == this.L && R == this.R) {
      return this.sum;
    }

    int M = (this.L + this.R) / 2;
    
    if (L > M) {
      return this.right.rangeQuery(L, R);
    } else if (R <= M) {
      return this.left.rangeQuery(L, R);
    } else {
      return (this.left.rangeQuery(L, M) +
        this.right.rangeQuery(M + 1, R));
    }
  }
}

Iterative DFS

Iterative PreOrder DFS

public static IList<int> PreOrderTraversal(TreeNode root)
{
  IList<int> result = new List<int>();
  if (root == null) return result;

  Stack<TreeNode> stack = new Stack<TreeNode>();
  stack.Push(root);

  while (stack.Count > 0)
  {
    TreeNode node = stack.Pop();
    result.Add(node.Val);

    // Push right child first so that left child is processed first
    if (node.Right != null)
    {
      stack.Push(node.Right);
    }
    if (node.Left != null)
    {
      stack.Push(node.Left);
    }
  }
  return result;
}

Iterative InOrder DFS

public static IList<int> InOrderTraversal(TreeNode root)
{
  IList<int> result = new List<int>();
  Stack<TreeNode> stack = new Stack<TreeNode>();
  TreeNode curr = root;

  while (curr != null || stack.Count > 0)
  {
    if (curr != null)
    {
      stack.Push(curr);
      curr = curr.Left;
    }
    else
    {
      curr = stack.Pop();
      result.Add(curr.Val);
      curr = curr.Right;
    }
  }

  return result;
}

Iterative PostOrder DFS

public static IList<int> PostOrderTraversal(TreeNode root)
{
  IList<int> result = new List<int>();

  if (root == null) return result;

  Stack<TreeNode> stack = new Stack<TreeNode>();
  TreeNode lastVisited = null;

  while (stack.Count > 0 || root != null)
  {
    if (root != null)
    {
      stack.Push(root);
      root = root.Left;
    }
    else
    {
      TreeNode peekNode = stack.Peek();
      if (peekNode.Right != null && lastVisited != peekNode.Right)
      {
        root = peekNode.Right;
      }
      else
      {
        result.Add(peekNode.Val);
        lastVisited = stack.Pop();
      }
    }
  }
  return result;
}

Two Heaps

Question: Implement a Median finder, where new values are inserted into the set, and you have to getMedian from that set. We will use two heaps one is MinHeap and the other is MaxHeap. MaxHeap will contain the first half of the (imaginary) current list and the MinHeap will contain the second half of it.

public class Median {
    private PriorityQueue<int, int> small;   // maxHeap
    private PriorityQueue<int, int> large;   // minHeap

    public Median() {
        // For the maxHeap, we invert the comparison to create a max-heap.
        small = new PriorityQueue<int, int>(Comparer<int>.Create((x, y) => y.CompareTo(x)));
        large = new PriorityQueue<int, int>();
    }
}

public void Insert(int num) {
    // Push to the max heap and swap with min heap if needed.
    small.Enqueue(num, num);
    if (small.Count > 0 && large.Count > 0 && small.Peek() > large.Peek()) {
        var val = small.Dequeue();
        large.Enqueue(val, val);
    }

    // Handle uneven size
    if (small.Count > large.Count + 1) {
        var val = small.Dequeue();
        large.Enqueue(val, val);
    } else if (large.Count > small.Count + 1) {
        var val = large.Dequeue();
        small.Enqueue(val, val);
    }
}

public double GetMedian() {
    if (small.Count > large.Count) {
        return small.Peek();
    } else if (large.Count > small.Count) {
        return large.Peek();
    }

    // Even number of elements, return average of the two middle numbers.
    return ((double)small.Peek() + large.Peek()) / 2;
}

Subsets:

Question: Given a list of distinct nums, return all possible distinct subsets.

// Time: O(n * 2^n), Space: O(n)
public static List<List<int>> SubsetsWithoutDuplicates(int[] nums) {
    List<List<int>> subsets = new List<List<int>>();
    List<int> curSet = new List<int>();
    Helper(0, nums, curSet, subsets);
    return subsets;
}

public static void Helper(int i, int[] nums, List<int> curSet, List<List<int>> subsets) {
    if (i >= nums.Length) {
        subsets.Add(new List<int>(curSet));
        return;
    }
    
    // decision to include nums[i]
    curSet.Add(nums[i]);
    Helper(i + 1, nums, curSet, subsets);
    curSet.RemoveAt(curSet.Count - 1);
    
    // decision NOT to include nums[i]
    Helper(i + 1, nums, curSet, subsets);
}

Question: Given a list of nums that are not necessarily distinct, return all possible distinct subsets.

// Time: O(n * 2^n), Space: O(n)
public static List<List<int>> SubsetsWithDuplicates(int[] nums) {
    Array.Sort(nums);
    List<int> curSet = new List<int>();
    List<List<int>> subsets = new List<List<int>>();
    Helper2(0, nums, curSet, subsets);
    return subsets;
}

public static void Helper2(int i, int[] nums, List<int> curSet, List<List<int>> subsets) {
    if (i >= nums.Length) {
        subsets.Add(new List<int>(curSet));
        return;
    }
    
    // decision to include nums[i]
    curSet.Add(nums[i]);
    Helper2(i + 1, nums, curSet, subsets);
    curSet.RemoveAt(curSet.Count - 1);

    // decision NOT to include nums[i]
    while (i + 1 < nums.Length && nums[i] == nums[i + 1]) {
        i++;
    }
    Helper2(i + 1, nums, curSet, subsets);
}

Time Space Complexity The time complexity would be because at every single element, we can either choose to include or not include that specific element. If we are given the list [1,2,3] to calculate all of the subsets for, we can only make two decisions at any given element and we are putting it all down in a decision tree, and 𝑛 n is the number of elements in set, it makes total sense that our algorithm runs in

The memory complexity should be considered the same, but sometimes the interviewer does not consider the input to be part of the time complexity. This would bring the space complexity to since n is not considered.

Combinations

Question: Given two nums n and k, return all possible combinations of size = k, choosing from values between 1 and n.

// Given n numbers (1 - n), return all possible combinations
// of size k. (n choose k math problem).
// Time: O(k * 2^n)
public static List<List<int>> Combinations(int n, int k) {
    List<List<int>> combs = new List<List<int>>();
    Helper(1, new List<int>(), combs, n, k);
    return combs;
}

public static void Helper(int i, List<int> curComb, List<List<int>> combs, int n, int k) {
    if (curComb.Count == k) {
        combs.Add(new List<int>(curComb));
        return;
    }
    if (i > n) {
        return;
    }
    // decision to include i
    curComb.Add(i);
    Helper(i + 1, curComb, combs, n, k);
    curComb.RemoveAt(curComb.Count - 1);
    
    // decision to NOT include i
    Helper(i + 1, curComb, combs, n, k);
}

Optimized Solution:

// Time: O(k * C(n, k))
public static List<List<int>> Combinations2(int n, int k) {
    List<List<int>> combs = new List<List<int>>();
    Helper2(1, new List<int>(), combs, n, k);
    return combs;
}

public static void Helper2(int i, List<int> curComb, List<List<int>> combs, int n, int k) {
    if (curComb.Count == k) {
        combs.Add(new List<int>(curComb));
        return;
    }
    if (i > n) {
        return;
    }
    for (int j = i; j < n + 1; j++) {
        curComb.Add(j);
        Helper2(j + 1, curComb, combs, n, k);
        curComb.RemoveAt(curComb.Count -1);
    }
}

Permutation

Question: Given a list of nums, return all possible distinct permutations of nums.

// Time: O(n^2 * n!)
public static List<List<int>> GetPermutations(int[] nums)
{
  List<List<int>> result = new();
  Helper(nums, 0, nums.Length-1, result);
  return result;
} 
// Time: O(n^2 * n!)

public static void Helper(int[] array, int l, int right, List<List<int>> result) {
  if (l == right) {
    result.Add(array.ToList());
    return;
  }

  for (int i=l; i<= right; i++) {
    Swap(ref array[i], ref array[l]);
    Helper(array, i+1, right, result);
    Swap(ref array[i], ref array[l]);
  }
}

public static void Swap(ref int i, ref int j) {
  int tmp = i;
  i = j;
  j = tmp;
}

Chapter 1: Computer Architecture

Wht not using a bigger and bigger CPUs? Mostly because CPU speeds reached a plateau.

Chapter 2: Application Architecture

What should you do when a server is not capable of serving your current load?

  • We can make the server a bit better: Better CPU, More RAM, etc. This is called vertical scaling.

  • We can take our server and make copy of it. This is called horizontal scaling.

Metric Service: provides all the metric we care about. How resources of the server is being utilized. Sometime this is actually log-based metrics.

  • When something goes wrong, we would'nt want to manually go and look at the metrics to understand something is wrong!
  • We feed the metric to another service called alerting service to automatically notify us when some performance falls behind some configured threshold.

Chapter 3: Design Requirements

High Level requirements:

  • Move Data
  • Store Data:
    • Usually on database
    • Blob store
    • File systems or distributed file systems
  • Transform Data

NOTE: Bad design choices for application architecture are very difficult to correct later. For example, if you design a database badly, it would hurt really bad.


Availability:

If a system has 99% availability, it experiences 1% downtime. By increasing availability to 99.9%, the downtime reduces significantly, from 1% to just 0.1%, representing a tenfold improvement. This increase is substantial, as even a small rise in availability dramatically minimizes potential disruptions. 99% is two-9s! :D

SLO: Service Level Objective SLA: Service Level Agreement which states if a company's service is interrupted, how the customer will be provided by partial refund.


Throughput

  • For user related transactions, it is # of requests / seconds
  • For Databases usually the throughput is measured as Queries/Second or QPS.
  • For pipelines where large data flows through different stages, byte / seconds is the metric

IPv4: 32-bit IPv6: 128-bit Port Number is a 16-bit value.

Sequence number in the TCP header

When sending a request to https://google.com browser reserves a port for your client machine on which you will receive the data back from the backend server.

TCP is reliable

  • IP does not have a solution for it.
  • Missing packets will be retransmitted
  • It is connection-oriented protocol and requires a physical connection be established before data can be exchanged
  • Full-Duplex
  • 3-way handshake
  • Data can be arrived out-of-order and reordered

UDP

  • User Datagram Protocol
  • Connection-Less
  • Some packet will be lost or arrive our of order: No guaranty
  • A lot faster than TCP
  • UDP is used for DNS for some reason

DNS

  • Domain Name System
  • ICANN: International Corporation for Assigned Names and Numbers
    • Non-Profit Organization: Does not sell the domains
    • Domain Registrar resell domains.
  • A Records is the main Address Records
  • On a URL: https://domains.google.com/get-started
    • com: is called TLD (Top Level Domain)
    • google: domain name or primary domain name
    • www: does not serve a technical purpose. It was mainly a convention to be used
    • /get-started: is a path

RPC: Remote Procedure Call, executing code that does not reside on the local machine.

HTTP:

  • Client and Server do not need to know anything about each other.
  • No state management
  • Anything needed for that request and response, is handled/included in the request/response.

Endpoint: A URL and a method like GET, PUT, ... is defined as an endpoint.

HTTP Responses:

  • Informational Responses: (100-199)
  • Successful Responses: (200-299)
    • 201 (created) which is a reasonable response for a POST request
  • Redirection Responses: (300-399)
  • Client error responses: (400-499)
  • Server error responses: (500-599)

SSL/TLS:

  • SSL: Secure Socket Layer
    • It came before TLS
    • It is outdated but still being used
  • TLS: Transport Layer Security

HTTPS:

  • Enhance HTTP against Man In The Middle (MITM) attack.

WebSocket:

  • It resolves an issue if you use http
    • Let's say you need to retrieve all the chat messages in a group
    • If you use HTTP, you need to frequently send requests to the server to send you the messages
    • It is some kind of polling. It might work but it is not optimized:
      • Every time it needs to make a new connection
  • Client sends a http request to establish a WebSocket connection
  • Going forward there is a persistent connection between the client and server
  • Now, the client and the server can be the initiator for a transaction.
    • For example a client starts typing a message. This will be delivered to everybody in the channel.
    • For other clients, the server is the initiator.

HTTP2: Added streams to its protocol and it will make WebSocket obsolete.


API: Application Programming Interface

Three of the modern APIs:

  • REST
  • GraphQL
  • gPRC

REST API:

  • REpresentation State Transfer
  • State-Less: There is not any server stored on the server
  • For example let's say we need to query all the comments for a Youtube video:
    • If we use pagination, we just send something like: https://youtube.com/videos?id=abc&offset=0&limit=10 which gives us the first 10 comments.
  • Being state-less helps in case of having multiple servers! No data needs to be saved!

JSON: Java Script Object Notation

  • Readable
  • From Performance perspective is not the best

GraphQL:

  • It is built on top of http
  • It only uses post request to be able to send data on the body which tells which resource is required to be retrieved from the server
  • When asking for resources, we end up with overfetching which means for example for a particular user we need the profile picture and the username. Not everything

gRPC:

  • Built on top of HTTP2 because it needs certain features of HTTP2
  • Cannot be used natively from a browser
  • You need a proxy
  • It is usually used for server-to-server communication
  • It is faster than REST
  • Instead of json it sends data using Protocol Buffers
  • leads to send smaller amount of data
  • Instead of responses as in REST, it uses error messages: custom error handling

Good API

Let's say you have a POST endpoint which requires a userId and the content. After a while you might need to add another field in the body.

  • You can make that extra field optional so that your endpoint is backward-compatible.
  • You can use versioning.

Let's talk about an API for tweets!

  • POST: https://api.twitter.com/v1.0/tweet and pass tweet text and userId
  • GET (to retrieve one tweet): https://api.twitter.com/v1.0/tweet/:id
  • DELETE (to retrieve on tweet): https://api.twitter.com/v1.0/tweet/:id
  • GET (to retrieve list of a user's tweet): We already used https://api.twitter.com/v1.0/tweet/:id. Therefore we need another path: https://api.twitter.com/v1.0/users/:id/tweets?limit=10&offset=0 (for pagination). We make limit and offset optional.

Caching

  • The response header called cache-control is the header that leads to caching a file from the browser
  • x-cache: HIT means the data was returned from cache

Write-Around Cache:

  • When we write the data directly into the primary place which is disk.
  • The first time when reading the data, it's gonna be a miss. Then we copy the data to the memory (cache).

Write-Through Cache:

  • When writing the data, it will be directly to the cache.

Write-Back Cache:

What is the difference between write-through and write-Back


CDN: Content Delivery Network

  • CDNs are used for static content that are not changing
  • Pull CDNs and Push CDNs

Proxies

Load Balancers are examples of reverse proxy.

Load balancing Strategies:

  • Round Robin
  • Weighted Round Robin
  • Number of Least Connections
  • Location
  • Hashing

There are two types of load balancers: Layer 4 (transport layer )and Layer 7 (Application layer)

  • Layer 4 is faster since it looks at the IP. Does not have higher levels' visibility
  • That's why layer 7 is more powerful. It is more expensive.

Note: Look at a paper by Google called Maglev.


Consistent Hashing (for Load Balancing)

Let's say you have multiple servers, each having their own on-memory cache. How can we make sure we use the best out of the cached data? For example when a server goes down or we add more servers. How can we make sure we map current requests to a server with cached data?

Note: You need to research this more thoroughly.

Note: Learn Rendezvous Caching


SQL

RDBMS: Relational DataBase Management Systems

  • SQL are stored on disk
  • Efficient Read and Write operations are necessary.
  • It uses B+ tree. TODO: study this

Tradeoff in using RDBMS:

  • Atomicity
    • We have transactions in database
    • Transactions should be atomic
    • If a portion of a transaction fails, the whole transaction should fail
      • For example you need to move money from one customer and add it to another one. What happens if you update the first customer's bank account value. But, before updating the second customer's, database crashes?
  • Consistency
    • Some columns should not be NULL.
    • Certain columns should be unique for example.
  • Isolation:
    • Transactions should not have any impact on each other when running in parallel (side effect).
    • We might need to enforce a sequence on transactions
  • Durability:
    • Data should be persisted
    • Redis is not durable and therefore not ACID-compliant

NoSQL (Not Only SQL)

The biggest limitation that NoSQL can get over is scale.

Examples of NoSQL:

  • Key-Value Stores: Redis, Memcached, etcd
    • Usually used for cache
  • Document Store:
    • More is like a collection for example a JSON
    • The benefit is that it is a lot more flexible
    • The most popular is MongoDB
  • Wide-Column:
    • A lot of writes like time series, less read and update
    • Might have schema as well
    • The most optimized for a massive amount of writing
    • Cassandra and Google's BigTable.
  • Graph DB:
    • Built on top of SQL in some ways
    • Efficient for example for Facebook Friendship use case

SQL vs NoSQL:

  • NoSQL dbs can generally scale a lot better than SQL dbs
    • Mostly because of the constraints on SQL: ACID
    • Scaling horizontally for SQL is quite difficult because of ACID
      • joining two data from two servers and enforcing the constraints, is really difficult
      • For NoSQL we don't have the constraints and therefore they can scale better
  • ACID for SQL is like BaSE for NoSQL
    • Eventual Consistency
    • Leader-Follower Concept:
      • We have two database that are supposed to be replicate of each other
      • Write should be on the leader database
      • Eventually the leader will make sure that the same data to the follower(S)
      • For a shorter amount of the time, if requests go to the followers, they might see non up-to-date values
      • We are able to handle higher amount of read capacity
  • Partitioning data is available for SQL databases as well: Sharding
    • by default is not implemented for SQLs
    • it is gonna be much more complicated. That's why not implemented by default.

Replication

Leader-Follower Replication: We talked about it a bit earlier.

  • Asynchronous vs. Synchronous Replication

Leader-Leader Replications:

  • Pros:
    • We can read and write from every single node, scaling up read as well write.
  • Cons:
    • Making consistency is gonna be difficult
  • Each master usually servers different part of the world, independently.

Sharding

  • When you massive amount of data, a single query can take seconds to complete.
  • We take half of the rows in one database in machine 1 and take the second half in another database in machine 2.
  • How dow we divide the data then?
    • We use shard key like female or male
      • Or like Last name from A-L goes to machine 1 and M-Z goes to machine 2
      • Running joins between two machine is gonna be complicated
    • Hash-based Sharding
  • SQL databases like MySQL and Postgres do not provide sharding by default. We should implement them ourselves.
  • Sharding are not designed to be used with RDBMS databases.

CAP Theorem

  • Consistency
  • Availaiblity
  • Partition Tolerance

It is like having two servers, one leader and follower. Partition Tolerance is when two servers cannot talk to each other. Now we have two options:

  • Prioritize Consistency which means we make followers unavailable
  • Prioritize Availability which means although some data are not up-to date, users can send request to them.

PACELC: Give P (network connection between servers working), choose A or C. Else, favor Latency or Consistency


Object Storage

The predecessors to Object Storage was blob storages.

BLOB: Binary Large OBjects.

  • When we put files there, we cannot edit that files.
  • Optimized to save a large amount of data
  • Similar to Hashmaps, your files' ID should globally unique

Use Cases:

  • When you storing large files that you need for your applications for long-term usages
  • Metadata can still be saved in databases
  • Storing large files in a database does not make sense
  • You can easily send one simple GET HTTP request and retrieve your file

Message Queues

  • When there are large number of events coming to a server and in case the server can not keep up with the events, message queues come into picture.
  • The data will be stored on disk
  • Usually events will be processed FIFO

Data transportation between queue and server:

  • Server can pull from the queue
  • Queue can push the data to the servers
    • Sometimes the server responds with an acknowledge

Pub/Sub:

  • There are multiple publishers that produce the events
  • A middle layer called Topics feed into different subscriptions

Note:

  • The benefit is that if one application or served is added, it can easily scale and adapt to the architecture by defining more topics and subscribers.
  • Popular message queues include RabbitMQ and Kafka
  • Popular cloud-based one is Google's pub/sub

MapReduce

  • We have a large amount of personal data
  • For each person we want to redact pipelines
  • If we need to process it quickly we might need multiple servers to process it in parallel

Now we have two types of processing:

  • Batch processing:
    • We have all the data upfront
    • Micro-batch processing is like processing a bunch of data every 30 seconds.
  • Streaming
    • We are processing data in real-time (data is coming)

Note:

  • Spark Cluster and Hadoop is examples of MapReduce. Probably Flink

Overview

  • Scoping out the question is important
  • Do not assume anything! Always ask for clarification!
  • Handling non-functional part of a design question might be more important:
  • Scalability
  • Throughput
  • Storage Capacity
  • Performance
  • Latency
  • Availability
    • Improving the availability of e.g. Twitter from 99.9999% (5 minutes/year) to 99.99999% (30 seconds/year) might not worth the effort! Tradeoff here is important.
Back of the envelope calculation

This is the calculation that you do on a piece of paper or on your mind instead of formally calculate it!

Design a Rate Limiter

  • It is used for security reasons
  • It is used for business reasons:
    • For example you cannot upload more than 20 videos in 24 hours!
      • You can upload lots of videos and use all the capacity available!
    • You cannot post more than for example 1,000,000 comments on a post
    • The main reason is essentially preventing bots to make too many request in a short period of time!

You can protect each microservice! However, it might be better to implement it as a bigger entity!

  • There could be multiple instances of a particular API and these need to be in sync with a time limiting service! Therefore, implementing a time limiter for each instance does not satisfy the requirements!

Discussion:

  • Implement the rate limiter on backend!
  • When the limit is reached, for a request we should send a 429 (rate limit error) HTTP response (this is not a server error! Instead it is a client error!)
  • Note: Can we implement a rate limiter from client-side code? Yep!
    • It is not sufficient! Because they can use our API!

How do we identify a user?

  • Should we use userId?
  • Instead it should be more general like IP address!

What is the latency/throughput implications?

What is the Storage implications?

What if the Rate Limiter goes down?

  • Fail-Open: if something in our system goes down, the whole system should continue working as if that component never existed
  • Fail-Closed: if something in our system goes down, the whole system should go down!

Let's design it now!

  • We need some type of storage to store our rules! It needs to be persistent!
  • Then, how the rate limiter knows for example how many videos are uploaded withing last 24 hours?
    • In-memory KV store like Redis cache.
  • What kind of algorithm for rate limiting?
    • Look at the Token Bucket and Sliding Window Counter algorithms

Design TinyUrl

Functional Requirements:

  • A long url should be mapped to a shorter url
    • It might be better to map to some words like happySOMETHING which is not always possible
  • Users might delete a Url if they own it which needs keeping tracking of the ownership.
  • Every Url should be expired after some time!
  • What would happen if multiple users attempt to map the same URL to a tinyUrl? Should all of them be mapped to the same TinyUrl?\
    • It is better to map it to different TinyUrl to for example have different expiration date for every owner

Non-Functional Requirements:

  • Make it reliable
  • What about the scale?
    • Is read more frequent or write?
    • Something 1B/Month write is reasonable?

Discussion:

  • If we can use digits, lowercase and uppercase, it gives us 62 characters to choose from: we can have 8-character urls which is about 256T. It then gives us almost 20000 Years! :|

  • 1B/Month is equal to roughly 385 write/second.

  • If write to read is 1:100 ratio, we end up with 38500 read/second.

  • What about the storage?

    • Let's say average of 100 characters per original Url and then we need to store userId and other stuff: around 1000 bytes/url
  • What kind of storage are we going to use?

    • More frequent reads
    • NoSQL is better since they are designed to be scalable.
    • It does NOT need complicated join queries
    • We do NOT need ACID or atomic transactions
    • Instead we need eventual consistency

Design:

  • A URL generator
  • Users will hit the main server first
  • The data will be stored in database
  • Since read are more frequently, we will use a cache for the database (in-memory cache like Redis)

Caching:

  • What kind of algorithm can we have? LFU or LRU
    • LRU seems better => A URL may experience a surge in traffic due to a trend, followed by a decline as the trend diminishes over time.
  • What should be the size of the cache?
    • 1TB/Month for write. However, not everything will be saved in the cache => 256GB for memory should be fine.

Url generation:

  • Hashing has the collision problem.
  • We can generate a list of 8-character and store them in a database. Whenever a new request comes in, we can use this list. When we fetch as key, we mark it as used!
    • Why not just easily remove a used key? After the key expires, we can re-use it.
  • What if two request goes to the database? How do we prevent assigning one key to both of them?
    • Atomic transaction in ACID will take care of it.

Remove expired urls:

  • It does not hurt if some urls get deleted after 10 minutes or so!
  • We need a cleanup service that run every 10 minutes for example.

Scalability

  • Use load balancer
  • Partition our database as well as replicas

How does it work in action?

  • If you browse to the tinyUrl, the server sends a 300 code, meaning the resource has been moved. There are two options here:
    • Code 301: the resource has been moved permanently to the new Url. The browser cache this information. Next time the browser automatically will send the complete Url.
    • Code 302: the resource has been temporarily moved to the new Url. The browser does not cache it.

LeetCode Questions

This section contains curated LeetCode practice plans organized by company and timeframe (30 / 90 / 180 days). Each page is a placeholder that you can fill with problem lists, solutions, and links to your code snippets.

Notes:

  • Fill each company's timeframe files (30 / 90 / 180) with problems and links to your implementations under rust_codes/problems or python_codes.

Amazon — LeetCode Plan

This page groups Amazon-focused practice plans.

Amazon — 30 Days

Problem List

Two Sum

Minimum Time To Complete All Deliveries

Add Two Numbers

Container With Most Water

Koko Eating Bananas

Longest Palindromic Substring

Number Of Islands

Avoid Flood In The City

Longest Substring Without Repeating Characters

Merge Intervals

Best Time To Buy And Sell Stock

Lru Cache

Longest Common Prefix

First Missing Positive

Trapping Rain Water

Group Anagrams

Add Binary

Word Search

Copy List With Random Pointer

Find Peak Element

Combine Two Tables

Create Hello World Function

Valid Parentheses

Merge K Sorted Lists

Remove Duplicates From Sorted Array

Search In Rotated Sorted Array

Rotate Image

Climbing Stairs

Set Matrix Zeroes

Same Tree

Majority Element

House Robber

Reverse Linked List

Coin Change

Next Greater Element I

Rotate String

Count Number Of Rectangles Containing Each Point

Make Array Elements Equal To Zero

Find The Minimum Amount Of Time To Brew Potions

Lexicographically Smallest Permutation Greater Than Target

Median Of Two Sorted Arrays

Palindrome Number

Letter Combinations Of A Phone Number

4sum

Remove Element

Find The Index Of The First Occurrence In A String

Maximum Subarray

Insert Interval

Edit Distance

Largest Rectangle In Histogram

Merge Sorted Array

Maximum Depth Of Binary Tree

Pascals Triangle

Longest Consecutive Sequence

Gas Station

Candy

Evaluate Reverse Polish Notation

Reverse Words In A String

Min Stack

Employees Earning More Than Their Managers

Rotate Array

Course Schedule Ii

Contains Duplicate

Lowest Common Ancestor Of A Binary Search Tree

Move Zeroes

Find The Duplicate Number

Find Median From Data Stream

Increasing Triplet Subsequence

Reverse String

Top K Frequent Elements

Design Hit Counter

Find K Pairs With Smallest Sums

Decode String

Evaluate Division

Pacific Atlantic Water Flow

Single Element In A Sorted Array

Managers With At Least 5 Direct Reports

Design Circular Queue

Maximum Average Subarray I

Valid Palindrome Ii

Daily Temperatures

Delete And Earn

Jewels And Stones

Swim In Rising Water

Boats To Save People

Analyze User Website Visit Pattern

Product Price At A Given Date

Sum Of Subarray Ranges

Successful Pairs Of Spells And Potions

Taking Maximum Energy From The Mystic Dungeon

Maximum Frequency Of An Element After Performing Operations I

Maximum Number Of Distinct Elements After Operations

Sum Of Perfect Square Ancestors

Back to AmazonLeetCode Index

Amazon — 90 Days

Problem List

Two Sum

Add Two Numbers

Longest Substring Without Repeating Characters

Lru Cache

Longest Palindromic Substring

Group Anagrams

Number Of Islands

Palindrome Number

Trapping Rain Water

Koko Eating Bananas

Container With Most Water

Longest Common Prefix

3sum

Valid Parentheses

Best Time To Buy And Sell Stock

Longest Consecutive Sequence

Median Of Two Sorted Arrays

Subarray Sum Equals K

Search In Rotated Sorted Array

Maximum Subarray

Merge Intervals

Reorganize String

Roman To Integer

Merge Two Sorted Lists

Word Search

Find Peak Element

Majority Element

Next Permutation

N Queens

Course Schedule

Merge K Sorted Lists

Reverse Nodes In K Group

Remove Duplicates From Sorted Array

Climbing Stairs

Top K Frequent Elements

Minimum Time To Complete All Deliveries

Letter Combinations Of A Phone Number

Search A 2d Matrix

Pascals Triangle

Copy List With Random Pointer

Combine Two Tables

Single Element In A Sorted Array

Fruit Into Baskets

Generate Parentheses

First Missing Positive

Rotate Array

House Robber

Course Schedule Ii

Lowest Common Ancestor Of A Binary Tree

Daily Temperatures

Reverse Integer

Regular Expression Matching

Merge Sorted Array

Binary Tree Level Order Traversal

Binary Tree Maximum Path Sum

Gas Station

Reverse Linked List

Sliding Window Maximum

Diameter Of Binary Tree

Rotting Oranges

Avoid Flood In The City

Confirmation Rate

Maximum K To Sort A Permutation

Remove Element

Find First And Last Position Of Element In Sorted Array

Add Binary

Sort Colors

Largest Rectangle In Histogram

Balanced Binary Tree

Populating Next Right Pointers In Each Node

Word Ladder

Happy Number

Contains Duplicate

Find Median From Data Stream

House Robber Iii

Partition Equal Subset Sum

Next Greater Element Ii

Managers With At Least 5 Direct Reports

Flood Fill

String To Integer Atoi

Search Insert Position

Jump Game

Sqrtx

Edit Distance

Binary Tree Zigzag Level Order Traversal

Min Stack

Largest Number

Meeting Rooms Ii

Missing Number

Coin Change

Intersection Of Two Arrays

Insert Delete Getrandom O1

Trapping Rain Water Ii

Split Array Largest Sum

Assign Cookies

Rotate Image

Spiral Matrix

Minimum Window Substring

Reverse Linked List Ii

Validate Binary Search Tree

Maximum Depth Of Binary Tree

Candy

Linked List Cycle

Employees Earning More Than Their Managers

Word Search Ii

Kth Largest Element In An Array

Maximal Square

Majority Element Ii

Power Of Two

Product Of Array Except Self

Valid Anagram

Move Zeroes

Find The Duplicate Number

Serialize And Deserialize Binary Tree

Power Of Three

Decode String

Pacific Atlantic Water Flow

String Compression

Lfu Cache

Next Greater Element I

Diagonal Traverse

Valid Triangle Number

Palindromic Substrings

Rotate String

All Nodes Distance K In Binary Tree

Minimum Add To Make Parentheses Valid

Analyze User Website Visit Pattern

Count Square Submatrices With All Ones

Check If Array Is Sorted And Rotated

Recyclable And Low Fat Products

Sum Of Subarray Ranges

Create Hello World Function

Count Bowl Subarrays

4sum

Find The Index Of The First Occurrence In A String

Valid Sudoku

Text Justification

Set Matrix Zeroes

Subsets

Same Tree

Surrounded Regions

Single Number

Insertion Sort List

Second Highest Salary

Delete Node In A Linked List

Game Of Life

Power Of Four

Find K Pairs With Smallest Sums

Ransom Note

Evaluate Division

Remove K Digits

Longest Repeating Character Replacement

Repeated Substring Pattern

Max Consecutive Ones

Task Scheduler

Design Circular Queue

Maximum Average Subarray I

Maximum Width Of Binary Tree

Asteroid Collision

Online Stock Span

Sum Of Subarray Minimums

Vowel Spellchecker

Capacity To Ship Packages Within D Days

Shortest Common Supersequence

Article Views I

Maximum Profit In Job Scheduling

Furthest Building You Can Reach

Maximum Units On A Truck

Plates Between Candles

Find Triangular Sum Of An Array

Number Of Zero Filled Subarrays

Smallest Missing Non Negative Integer After Operations

Minimum Operations To Make The Integer Zero

Count Elements With Maximum Frequency

Find The Number Of Ways To Place People I

Taking Maximum Energy From The Mystic Dungeon

Find The Minimum Area To Cover All Ones Ii

Find The Minimum Amount Of Time To Brew Potions

Lexicographically Smallest Permutation Greater Than Target

Zigzag Conversion

Substring With Concatenation Of All Words

Longest Valid Parentheses

Sudoku Solver

Count And Say

Jump Game Ii

Powx N

Length Of Last Word

Rotate List

Unique Paths

Simplify Path

Remove Duplicates From Sorted List

Maximal Rectangle

Binary Tree Inorder Traversal

Distinct Subsequences

Triangle

Best Time To Buy And Sell Stock Ii

Palindrome Partitioning Ii

Clone Graph

Word Break

Linked List Cycle Ii

Sort List

Reverse Words In A String

Two Sum Ii Input Array Is Sorted

Delete Duplicate Emails

Rising Temperature

Binary Tree Right Side View

Remove Linked List Elements

Isomorphic Strings

Contains Duplicate Ii

Basic Calculator Ii

Lowest Common Ancestor Of A Binary Search Tree

Search A 2d Matrix Ii

Integer To English Words

Find The Celebrity

First Bad Version

Range Sum Query Immutable

Number Of Connected Components In An Undirected Graph

Odd Even Linked List

Reverse String

Russian Doll Envelopes

Design Twitter

Insert Delete Getrandom O1 Duplicates Allowed

Is Subsequence

Add Strings

All Oone Data Structure

Non Overlapping Intervals

Arranging Coins

Delete Node In A Bst

Predict The Winner

Contiguous Array

Permutation In String

Longest Harmonious Subsequence

Smallest Range Covering Elements From K Lists

Valid Palindrome Ii

Binary Search

Delete And Earn

Open The Lock

Partition Labels

Swim In Rising Water

New 21 Game

Boats To Save People

Minimum Falling Path Sum

Distribute Coins In Binary Tree

Time Based Key Value Store

Vertical Order Traversal Of A Binary Tree

Subarrays With K Different Integers

Immediate Food Delivery Ii

Unique Number Of Occurrences

Find The Smallest Divisor Given A Threshold

Find N Unique Integers Sum Up To Zero

Convert Integer To The Sum Of Two No Zero Integers

Percentage Of Users Attended A Contest

Swapping Nodes In A Linked List

Minimum Number Of People To Teach

Minimum Difference Between Highest And Lowest Of K Scores

Count Number Of Rectangles Containing Each Point

Successful Pairs Of Spells And Potions

Number Of People Aware Of A Secret

Range Product Queries Of Powers

Count Subarrays With Median K

Ways To Express An Integer As Sum Of Powers

Score Of A String

Maximum Total Damage With Spell Casting

Find The Minimum Area To Cover All Ones I

Delete Nodes From Linked List Present In Array

Make Array Elements Equal To Zero

Maximum Number Of Distinct Elements After Operations

Sort Matrix By Diagonals

Length Of Longest V Shaped Diagonal Segment

Remove Nth Node From End Of List

Swap Nodes In Pairs

Divide Two Integers

Combination Sum

Permutations

Permutations Ii

N Queens Ii

Insert Interval

Spiral Matrix Ii

Minimum Path Sum

Plus One

Search In Rotated Sorted Array Ii

Scramble String

Recover Binary Search Tree

Symmetric Tree

Path Sum

Flatten Binary Tree To Linked List

Palindrome Partitioning

Word Break Ii

Evaluate Reverse Polish Notation

Maximum Product Subarray

Fraction To Recurring Decimal

Dungeon Game

Nth Highest Salary

Rank Scores

Consecutive Numbers

Department Highest Salary

Department Top Three Salaries

Reverse Bits

Bitwise And Of Numbers Range

Minimum Size Subarray Sum

Design Add And Search Words Data Structure

House Robber Ii

Shortest Palindrome

Basic Calculator

Implement Stack Using Queues

Invert Binary Tree

Kth Smallest Element In A Bst

Implement Queue Using Stacks

Ugly Number

Burst Balloons

Shortest Distance From All Buildings

Increasing Triplet Subsequence

Design Tic Tac Toe

Design Hit Counter

Largest Divisible Subset

First Unique Character In A String

Fizz Buzz

Path Sum Iii

Find All Anagrams In A String

Add Two Numbers Ii

Island Perimeter

Reverse Pairs

Target Sum

Base 7

Perfect Number

Fibonacci Number

Game Play Analysis I

Longest Palindromic Subsequence

Number Of Provinces

Array Partition

Investments In 2016

Big Countries

Exclusive Time Of Functions

Set Mismatch

Find K Closest Elements

Strange Printer

Valid Parenthesis String

Count Binary Substrings

Degree Of An Array

Design Linked List

Subarray Product Less Than K

Maximum Length Of Repeated Subarray

My Calendar I

Jewels And Stones

Is Graph Bipartite

Cheapest Flights Within K Stops

Soup Servings

Largest Triangle Area

Peak Index In A Mountain Array

Lemonade Change

Shortest Subarray With Sum At Least K

Transpose Matrix

Reordered Power Of 2

Leaf Similar Trees

Nth Magical Number

Maximum Frequency Stack

Sort Array By Parity

Sort Array By Parity Ii

Most Stones Removed With Same Row Or Column

Binary Tree Cameras

Squares Of A Sorted Array

Max Consecutive Ones Iii

Next Greater Node In Linked List

Robot Bounded In Circle

Customers Who Bought All Products

Last Stone Weight

Remove All Adjacent Duplicates In String

Longest String Chain

Car Pooling

Find In Mountain Array

Defanging An Ip Address

N Th Tribonacci Number

Longest Common Subsequence

Product Price At A Given Date

Design File System

Critical Connections In A Network

Sort Items By Groups Respecting Dependencies

Remove All Adjacent Duplicates In String Ii

Search Suggestions System

Students And Examinations

Minimum Insertion Steps To Make A String Palindrome

Number Of Operations To Make Network Connected

Restaurant Growth

Maximum 69 Number

How Many Numbers Are Smaller Than The Current Number

Maximum Sum Bst In Binary Tree

Longest Continuous Subarray With Absolute Diff Less Than Or Equal To Limit

Running Sum Of 1d Array

Minimum Number Of Days To Make M Bouquets

Number Of Subsequences That Satisfy The Given Sum Condition

Count Submatrices With All Ones

Kth Missing Positive Number

Make The String Great

Magnetic Force Between Two Balls

Customer Who Visited But Did Not Make Any Transactions

Min Cost To Connect All Points

Even Odd Tree

Lexicographically Smallest String After Applying Operations

Average Time Of Process Per Machine

The Number Of Employees Which Report To Each Employee

Minimum Limit Of Balls In A Bag

Merge Strings Alternately

Primary Department For Each Employee

Frequency Of The Most Frequent Element

Find A Peak Element Ii

Count Good Numbers

Final Value Of Variable After Performing Operations

Most Beautiful Item For Each Query

Minimum Sum Of Four Digit Number After Splitting Digits

Minimum Time To Complete Trips

Maximum Candies Allocated To K Children

Count Unreachable Pairs Of Nodes In An Undirected Graph

Maximum Sum Of Distinct Subarrays With Length K

Minimize The Maximum Difference Of Pairs

Sleep

Find The Maximum Achievable Number

Water Bottles Ii

Maximum Frequency Of An Element After Performing Operations I

Design Task Manager

Maximum Frequency After Subarray Operation

Fruits Into Baskets Ii

Fruits Into Baskets Iii

Find Most Frequent Vowel And Consonant

Minimum Operations To Equalize Binary String

Sum Of Perfect Square Ancestors

Back to AmazonLeetCode Index

Amazon — 180 Days

Problem List

Two Sum

Lru Cache

Longest Substring Without Repeating Characters

Number Of Islands

Best Time To Buy And Sell Stock

Longest Palindromic Substring

Trapping Rain Water

Add Two Numbers

Reorganize String

Group Anagrams

Container With Most Water

Merge Intervals

Subarray Sum Equals K

Koko Eating Bananas

Median Of Two Sorted Arrays

Palindrome Number

3sum

Valid Parentheses

Course Schedule

Maximum Subarray

Rotting Oranges

Longest Common Prefix

Top K Frequent Elements

Lowest Common Ancestor Of A Binary Tree

Generate Parentheses

Merge K Sorted Lists

Word Search

Maximum Frequency After Subarray Operation

Next Permutation

Search In Rotated Sorted Array

Longest Consecutive Sequence

Copy List With Random Pointer

Find Peak Element

House Robber

Find First And Last Position Of Element In Sorted Array

Search A 2d Matrix

Roman To Integer

Merge Two Sorted Lists

Minimum Window Substring

Majority Element

Product Of Array Except Self

Jump Game

Merge Sorted Array

Pascals Triangle

Course Schedule Ii

Jump Game Ii

N Queens

Meeting Rooms Ii

Analyze User Website Visit Pattern

Reverse Integer

Binary Tree Maximum Path Sum

Single Element In A Sorted Array

Remove Duplicates From Sorted Array

Edit Distance

Word Ladder

Capacity To Ship Packages Within D Days

Letter Combinations Of A Phone Number

Spiral Matrix

Climbing Stairs

Reverse Linked List

Sliding Window Maximum

Find Median From Data Stream

Coin Change

Insert Delete Getrandom O1

Longest Repeating Character Replacement

Minimum Number Of Primes To Sum To Target

Reverse Nodes In K Group

Single Number

Min Stack

Asteroid Collision

Valid Sudoku

Rotate Image

Kth Largest Element In An Array

Valid Anagram

Find The Duplicate Number

Flood Fill

Remove Element

First Missing Positive

Unique Paths

Largest Rectangle In Histogram

Binary Tree Level Order Traversal

Best Time To Buy And Sell Stock Ii

Candy

Missing Number

Fruit Into Baskets

Search Insert Position

Serialize And Deserialize Binary Tree

Pacific Atlantic Water Flow

Concatenated Words

String To Integer Atoi

Sort Colors

Binary Tree Zigzag Level Order Traversal

Word Break

Rotate Array

Contains Duplicate

String Compression

Next Greater Element Ii

Regular Expression Matching

Sudoku Solver

Combination Sum

Word Break Ii

Reverse Words In A String

Largest Number

Binary Tree Right Side View

Move Zeroes

Evaluate Division

Max Consecutive Ones Iii

Zigzag Conversion

Permutations

Populating Next Right Pointers In Each Node

Surrounded Regions

Combine Two Tables

Happy Number

Word Search Ii

Odd Even Linked List

Intersection Of Two Arrays

Diameter Of Binary Tree

Daily Temperatures

Integer To Roman

Set Matrix Zeroes

Validate Binary Search Tree

Balanced Binary Tree

Gas Station

Linked List Cycle

House Robber Iii

Lfu Cache

Next Greater Element I

Maximum K To Sort A Permutation

Minimum Time To Complete All Deliveries

4sum

Find The Index Of The First Occurrence In A String

Add Binary

Subsets

Maximal Rectangle

Construct Binary Tree From Preorder And Inorder Traversal

Employees Earning More Than Their Managers

Invert Binary Tree

Decode String

Trapping Rain Water Ii

Partition Equal Subset Sum

All Nodes Distance K In Binary Tree

Middle Of The Linked List

Maximum Profit In Job Scheduling

Rotate List

Remove Duplicates From Sorted Array Ii

Same Tree

Palindrome Partitioning

Two Sum Ii Input Array Is Sorted

Contains Duplicate Ii

Maximal Square

Basic Calculator

Majority Element Ii

Palindrome Linked List

Integer To English Words

First Unique Character In A String

Split Array Largest Sum

Fizz Buzz

Diagonal Traverse

Task Scheduler

Palindromic Substrings

Article Views I

Recyclable And Low Fat Products

Frequency Of The Most Frequent Element

Maximize Ysum By Picking A Triplet Of Distinct Xvalues

Process String With Special Operations I

Powx N

Sqrtx

Simplify Path

Sort List

Maximum Product Subarray

Second Highest Salary

Number Of Connected Components In An Undirected Graph

Assign Cookies

Number Of Provinces

Rotate String

K Closest Points To Origin

Time Based Key Value Store

Vertical Order Traversal Of A Binary Tree

Check If Array Is Sorted And Rotated

Confirmation Rate

Create Hello World Function

Count Zero Request Servers

Find The Median Of The Uniqueness Array

3sum Closest

Remove Nth Node From End Of List

Longest Valid Parentheses

Text Justification

Decode Ways

Reverse Linked List Ii

Recover Binary Search Tree

Convert Sorted Array To Binary Search Tree

Evaluate Reverse Polish Notation

Rising Temperature

Minimum Size Subarray Sum

Kth Smallest Element In A Bst

Design Tic Tac Toe

Find K Pairs With Smallest Sums

Remove K Digits

Target Sum

Fibonacci Number

Random Pick With Weight

Managers With At Least 5 Direct Reports

Maximum Width Of Binary Tree

Max Area Of Island

Binary Search

Open The Lock

Peak Index In A Mountain Array

Online Stock Span

Maximum Number Of Events That Can Be Attended

Replace Employee Id With The Unique Identifier

Maximum Number Of Vowels In A Substring Of Given Length

Avoid Flood In The City

Sum Of Subarray Ranges

Divide Two Integers

Minimum Path Sum

Combinations

Remove Duplicates From Sorted List

Unique Binary Search Trees

Distinct Subsequences

Single Number Ii

Reorder List

Binary Search Tree Iterator

Dungeon Game

Isomorphic Strings

House Robber Ii

Implement Stack Using Queues

Power Of Two

Delete Node In A Linked List

Longest Increasing Subsequence

Russian Doll Envelopes

Predict The Winner

Reverse Pairs

01 Matrix

Design In Memory File System

Course Schedule Iii

Find Eventual Safe States

Making A Large Island

Sum Of Subarray Minimums

Snakes And Ladders

Minimum Falling Path Sum

Unique Number Of Occurrences

Count Square Submatrices With All Ones

Maximum Points You Can Obtain From Cards

Longest Continuous Subarray With Absolute Diff Less Than Or Equal To Limit

Design Parking System

Furthest Building You Can Reach

Average Time Of Process Per Machine

Plates Between Candles

Fruits Into Baskets Ii

Substring With Concatenation Of All Words

Length Of Last Word

Subsets Ii

Binary Tree Inorder Traversal

Maximum Depth Of Binary Tree

Triangle

Valid Palindrome

Rank Scores

Count Primes

Implement Trie Prefix Tree

Basic Calculator Ii

Lowest Common Ancestor Of A Binary Search Tree

Search A 2d Matrix Ii

Find The Celebrity

Game Of Life

Design Hit Counter

Is Subsequence

All Oone Data Structure

Minimum Genetic Mutation

Non Overlapping Intervals

Repeated Substring Pattern

Max Consecutive Ones

Longest Harmonious Subsequence

Big Countries

Valid Triangle Number

Exclusive Time Of Functions

Maximum Average Subarray I

Find K Closest Elements

Valid Palindrome Ii

Top K Frequent Words

Partition Labels

Swim In Rising Water

Cheapest Flights Within K Stops

Soup Servings

Bus Routes

Boats To Save People

Binary Tree Cameras

Subarrays With K Different Integers

Largest 1 Bordered Square

Maximum Subarray Sum With One Deletion

Search Suggestions System

Minimum Number Of Days To Make M Bouquets

Min Cost To Connect All Points

Maximum Erasure Value

Maximum Units On A Truck

Maximum Difference Between Increasing Elements

Find All Possible Recipes From Given Supplies

Minimum Difference In Sums After Removal Of Elements

Amount Of Time For Binary Tree To Be Infected

Lexicographically Minimum String After Removing Stars

Find The Minimum Area To Cover All Ones Ii

Count Bowl Subarrays

Swap Nodes In Pairs

N Queens Ii

Spiral Matrix Ii

Plus One

Scramble String

Clone Graph

Linked List Cycle Ii

Find Minimum In Rotated Sorted Array

Intersection Of Two Linked Lists

Delete Duplicate Emails

Remove Linked List Elements

Ugly Number

Alien Dictionary

First Bad Version

Range Sum Query Immutable

Remove Duplicate Letters

Power Of Three

Reverse String

Insert Delete Getrandom O1 Duplicates Allowed

Ransom Note

Heaters

Permutation In String

Find Customer Referee

Design Circular Queue

Smallest Range Covering Elements From K Lists

Kth Largest Element In A Stream

Find Pivot Index

Min Cost Climbing Stairs

Maximize Distance To Closest Person

Car Fleet

Minimum Add To Make Parentheses Valid

Subarray Sums Divisible By K

Customers Who Bought All Products

Last Stone Weight

Product Sales Analysis Iii

Shortest Common Supersequence

Critical Connections In A Network

Monthly Transactions I

Average Selling Price

Find N Unique Integers Sum Up To Zero

Magnetic Force Between Two Balls

Customer Who Visited But Did Not Make Any Transactions

Lowest Common Ancestor Of A Binary Tree Iii

Merge Strings Alternately

Count Good Numbers

Minimum Cost To Reach Destination In Time

Kth Smallest Product Of Two Sorted Arrays

Rearrange Array Elements By Sign

Number Of Zero Filled Subarrays

Meeting Rooms Iii

Using A Robot To Print The Lexicographically Smallest String

Range Product Queries Of Powers

Maximum Sum Of Distinct Subarrays With Length K

Minimize The Maximum Difference Of Pairs

Minimum Operations To Make The Integer Zero

Ways To Express An Integer As Sum Of Powers

Count Elements With Maximum Frequency

Find The Number Of Ways To Place People I

Find The Minimum Area To Cover All Ones I

Reschedule Meetings For Maximum Free Time I

Maximize Subarrays After Removing One Conflicting Pair

Lexicographically Smallest Permutation Greater Than Target

Count And Say

Multiply Strings

Unique Paths Ii

Valid Number

Partition List

Unique Binary Search Trees Ii

Path Sum

Flatten Binary Tree To Linked List

Sum Root To Leaf Numbers

Insertion Sort List

Number Of 1 Bits

Design Add And Search Words Data Structure

Implement Queue Using Stacks

H Index

Binary Tree Vertical Order Traversal

Shortest Distance From All Buildings

Reconstruct Itinerary

Power Of Four

Design Twitter

Sum Of Two Integers

Lexicographical Numbers

Valid Word Abbreviation

Longest Palindrome

Add Strings

K Th Smallest In Lexicographical Order

Arranging Coins

Delete Node In A Bst

Can I Win

Contiguous Array

Next Greater Element Iii

Array Partition

Exchange Seats

2 Keys Keyboard

Valid Parenthesis String

Is Graph Bipartite

New 21 Game

Keys And Rooms

Reordered Power Of 2

Maximum Frequency Stack

Sort Array By Parity

Flip String To Monotone Increasing

Binary Subarrays With Sum

Reorder Data In Log Files

Vowel Spellchecker

Construct Binary Search Tree From Preorder Traversal

Next Greater Node In Linked List

Remove All Adjacent Duplicates In String

Smallest Subsequence Of Distinct Characters

Shortest Path In Binary Matrix

User Activity For The Past 30 Days I

Longest Common Subsequence

Design File System

Find The Smallest Divisor Given A Threshold

Number Of Operations To Make Network Connected

Movie Rating

How Many Numbers Are Smaller Than The Current Number

Maximum Sum Bst In Binary Tree

Kth Missing Positive Number

Percentage Of Users Attended A Contest

Maximum Number Of Events That Can Be Attended Ii

Primary Department For Each Employee

Find If Path Exists In Graph

Minimum Difference Between Highest And Lowest Of K Scores

Step By Step Directions From A Binary Tree Node To Another

Find Triangular Sum Of An Array

Add Two Integers

Successful Pairs Of Spells And Potions

Number Of People Aware Of A Secret

Removing Stars From A String

Count Subarrays With Median K

Smallest Missing Non Negative Integer After Operations

Minimum Equal Sum Of Two Arrays After Replacing Zeros

Find Missing And Repeated Values

Valid Word

Taking Maximum Energy From The Mystic Dungeon

Maximum Total Damage With Spell Casting

Delete Nodes From Linked List Present In Array

Count The Number Of Substrings With Dominant Ones

Find The Original Typed String I

Find The Original Typed String Ii

Maximum Frequency Of An Element After Performing Operations I

Design Task Manager

Length Of Longest V Shaped Diagonal Segment

Maximum Unique Subarray Sum After Deletion

Find The Minimum Amount Of Time To Brew Potions

Maximum Balanced Shipments

Maximum Total From Optimal Activation Order

Combination Sum Ii

Wildcard Matching

Insert Interval

Gray Code

Symmetric Tree

Path Sum Ii

Word Ladder Ii

Palindrome Partitioning Ii

Excel Sheet Column Title

Nth Highest Salary

Consecutive Numbers

Department Top Three Salaries

Shortest Palindrome

Combination Sum Iii

The Skyline Problem

Summary Ranges

Number Of Digit One

Meeting Rooms

Add Digits

Walls And Gates

Word Pattern

Nim Game

Bulls And Cows

Range Sum Query 2d Immutable

Burst Balloons

Bulb Switcher

Increasing Triplet Subsequence

Flatten Nested List Iterator

Reverse Vowels Of A String

Logger Rate Limiter

Largest Divisible Subset

Find The Difference

Longest Substring With At Least K Repeating Characters

Frog Jump

Flatten A Multilevel Doubly Linked List

Find All Anagrams In A String

Sort Characters By Frequency

Island Perimeter

Optimal Account Balancing

Base 7

Perfect Number

Coin Change Ii

Boundary Of Binary Tree

Reverse Words In A String Iii

Shortest Unsorted Continuous Subarray

Investments In 2016

Human Traffic Of Stadium

Can Place Flowers

Find Duplicate File In System

Design Search Autocomplete System

Set Mismatch

Trim A Binary Search Tree

Number Of Distinct Islands

Count Binary Substrings

Search In A Binary Search Tree

Insert Into A Binary Search Tree

Design Linked List

Subarray Product Less Than K

Maximum Length Of Repeated Subarray

Accounts Merge

Number Of Atoms

Delete And Earn

Find Smallest Letter Greater Than Target

Jewels And Stones

Basic Calculator Iii

K Th Symbol In Grammar

All Paths From Source To Target

Mirror Reflection

Lemonade Change

Shortest Subarray With Sum At Least K

Transpose Matrix

Nth Magical Number

Possible Bipartition

Number Of Recent Calls

Most Stones Removed With Same Row Or Column

Squares Of A Sorted Array

Distribute Coins In Binary Tree

Divisor Game

Minimum Score Triangulation Of Polygon

Lexicographically Smallest Equivalent String

Parsing A Boolean Expression

Defanging An Ip Address

Shortest Path With Alternating Colors

N Th Tribonacci Number

Immediate Food Delivery Ii

Remove All Adjacent Duplicates In String Ii

Queries Quality And Percentage

Minimum Insertion Steps To Make A String Palindrome

Convert Integer To The Sum Of Two No Zero Integers

Restaurant Growth

Check If N And Its Double Exist

Kids With The Greatest Number Of Candies

Max Difference You Can Get From Changing An Integer

Number Of Subsequences That Satisfy The Given Sum Condition

Count Submatrices With All Ones

Number Of Sub Arrays With Odd Sum

Even Odd Tree

Minimum Operations To Reduce X To Zero

Swapping Nodes In A Linked List

The Number Of Employees Which Report To Each Employee

Find The Highest Altitude

Minimum Number Of People To Teach

Sum Of Unique Elements

Minimum Number Of Operations To Move All Balls To Each Box

Sum Of Beauty Of All Substrings

Maximum Average Pass Ratio

Build Array From Permutation

Gcd Sort Of An Array

Detonate The Maximum Bombs

Minimum Operations To Make The Array Alternating

Minimum Time To Complete Trips

Find All K Distant Indices In An Array

Count Hills And Valleys In An Array

Count Number Of Rectangles Containing Each Point

Escape The Spreading Fire

Count Unreachable Pairs Of Nodes In An Undirected Graph

Smallest Number In Infinite Set

Best Poker Hand

Maximum Tastiness Of Candy Basket

Minimum Operations To Reduce An Integer To 0

Array Prototype Last

Filter Elements From Array

Row With Maximum Ones

Find The Maximum Achievable Number

Longest Non Decreasing Subarray From Two Arrays

Divisible And Non Divisible Sums Difference

Divide Array Into Arrays With Max Difference

Score Of A String

Find The Maximum Length Of Valid Subsequence I

Find The Maximum Length Of Valid Subsequence Ii

Find The K Th Character In String Game Ii

Make Array Elements Equal To Zero

Zero Array Transformation I

Maximum Number Of Distinct Elements After Operations

Sort Matrix By Diagonals

Fruits Into Baskets Iii

Permutations Ii

Permutation Sequence

Search In Rotated Sorted Array Ii

Remove Duplicates From Sorted List Ii

Restore Ip Addresses

Construct Binary Tree From Inorder And Postorder Traversal

Minimum Depth Of Binary Tree

Best Time To Buy And Sell Stock Iii

Compare Version Numbers

Fraction To Recurring Decimal

Excel Sheet Column Number

Factorial Trailing Zeroes

Duplicate Emails

Customers Who Never Order

Department Highest Salary

Repeated Dna Sequences

Reverse Bits

Bitwise And Of Numbers Range

Count Complete Tree Nodes

Different Ways To Add Parentheses

Binary Tree Paths

Encode And Decode Strings

Best Meeting Point

Number Of Islands Ii

Minimum Height Trees

Longest Increasing Path In A Matrix

Patching Array

Counting Bits

Nested List Weight Sum

Maximum Xor Of Two Numbers In An Array

Convert Binary Search Tree To Sorted Doubly Linked List

N Ary Tree Level Order Traversal

Number Of Segments In A String

Path Sum Iii

Find All Duplicates In An Array

Add Two Numbers Ii

Minimum Number Of Arrows To Burst Balloons

Minimum Moves To Equal Array Elements

Hamming Distance

Sliding Window Median

Relative Ranks

Game Play Analysis I

Longest Palindromic Subsequence

Continuous Subarray Sum

Convert Bst To Greater Tree

Reverse String Ii

Game Play Analysis Iv

Subtree Of Another Tree

Out Of Boundary Paths

Employee Bonus

Friend Requests Ii Who Has The Most Friends

Triangle Judgement

Not Boring Movies

Average Of Levels In Binary Tree

Maximum Length Of Pair Chain

Image Smoother

Strange Printer

Longest Continuous Increasing Subsequence

Degree Of An Array

Design Hashmap

Number Of Distinct Islands Ii

Max Stack

My Calendar I

Network Delay Time

Employee Free Time

Number Of Matching Subsequences

Largest Triangle Area

Most Common Word

Backspace String Compare

Loud And Rich

Leaf Similar Trees

Sort An Array

Maximum Sum Circular Subarray

Sort Array By Parity Ii

Shortest Bridge

Valid Mountain Array

Reveal Cards In Increasing Order

Unique Paths Iii

Minimum Cost For Tickets

Interval List Intersections

Find The Town Judge

Find Common Characters

Stream Of Characters

Uncrossed Lines

Binary Search Tree To Greater Sum Tree

Robot Bounded In Circle

Longest String Chain

Greatest Common Divisor Of Strings

Car Pooling

Find In Mountain Array

Parallel Courses

Product Price At A Given Date

Minimum Cost To Connect Sticks

Invalid Transactions

Sort Items By Groups Respecting Dependencies

Last Person To Fit In The Bus

Minimum Cost To Move Chips To The Same Position

Count Number Of Nice Subarrays

Count Servers That Communicate

Students And Examinations

Shortest Path In A Grid With Obstacles Elimination

Find Numbers With Even Number Of Digits

Maximum 69 Number

Minimum Number Of Taps To Open To Water A Garden

Angle Between Hands Of A Clock

Number Of Substrings Containing All Three Characters

Find Lucky Integer In An Array

Destination City

Shuffle The Array

Design Browser History

Running Sum Of 1d Array

The Kth Factor Of N

Longest Subarray Of 1s After Deleting One Element

Make The String Great

Maximum Nesting Depth Of The Parentheses

Lexicographically Smallest String After Applying Operations

Minimum Deletions To Make Character Frequencies Unique

Defuse The Bomb

Fix Names In A Table

Richest Customer Wealth

Number Of Students Unable To Eat Lunch

Maximum Score From Removing Substrings

Minimum Length Of String After Deleting Similar Ends

Minimum Limit Of Balls In A Bag

Finding The Users Active Minutes

Sorting The Sentence

Check If All The Integers In A Range Are Covered

Find A Peak Element Ii

Nearest Exit From Entrance In Maze

Painting A Grid With Three Different Colors

Last Day Where You Can Still Cross

Reverse Prefix Of Word

Final Value Of Variable After Performing Operations

Maximum Alternating Subarray Sum

Find The Minimum And Maximum Number Of Nodes Between Critical Points

Count Vowel Substrings Of A String

Minimized Maximum Of Products Distributed To Any Store

Most Beautiful Item For Each Query

Finding 3 Digit Even Numbers

Find Subsequence Of Length K With The Largest Sum

Maximum Fruits Harvested After At Most K Steps

Maximum Number Of Words Found In Sentences

Minimum Sum Of Four Digit Number After Splitting Digits

All Ancestors Of A Node In A Directed Acyclic Graph

Maximum Candies Allocated To K Children

Minimum Rounds To Complete All Tasks

Count Nodes Equal To Average Of Subtree

Number Of Ways To Split Array

Find Resultant Array After Removing Anagrams

Sum Of Total Strength Of Wizards

Apply Discount To Prices

Task Scheduler Ii

Find The K Sum Of An Array

Optimal Partition Of String

Smallest Subarrays With Maximum Bitwise Or

Longest Subarray With Maximum Bitwise And

Largest Positive Integer That Exists With Its Negative

Minimum Fuel Cost To Report To The Capital

Delete Greatest Value In Each Row

Put Marbles In Bags

Maximum Difference By Remapping A Digit

Sleep

Cache With Time Limit

Cousins In Binary Tree Ii

Buy Two Chocolates

Maximum Beauty Of An Array After Applying Operation

Count Complete Subarrays In An Array

Reshape Data Melt

Distribute Candies Among Children Ii

Maximum Size Of A Set After Removals

Water Bottles Ii

String Compression Iii

Minimum Amount Of Damage Dealt To Bob

Find The K Th Character In String Game I

Minimize The Maximum Adjacent Element Difference

Count Subarrays Of Length Three With A Condition

Find The Lexicographically Largest String From The Box I

Maximum Difference Between Adjacent Elements In A Circular Array

Maximum And Minimum Sums Of At Most Size K Subsequences

Find Valid Pair Of Adjacent Digits In String

Reschedule Meetings For Maximum Free Time Ii

Maximum Difference Between Even And Odd Frequency I

Unique 3 Digit Even Numbers

Minimum Pair Removal To Sort Array I

Find Closest Person

Find Most Frequent Vowel And Consonant

Minimum Operations To Convert All Elements To Zero

Longest Common Prefix Between Adjacent Strings After Removals

Minimum Operations To Equalize Binary String

Sum Of Perfect Square Ancestors

Back to AmazonLeetCode Index

Apple — LeetCode Plan

This page groups Apple-focused practice plans.

Apple — 30 Days

Merge Intervals

Lru Cache

Rotate Image

Maximum Subarray

Reverse Linked List

Design Hit Counter

Maximum Path Quality Of A Graph

Two Sum

Merge K Sorted Lists

Spiral Matrix

Rotate Array

Course Schedule

Course Schedule Ii

Basic Calculator Ii

Product Of Array Except Self

Find Median From Data Stream

Serialize And Deserialize Binary Tree

Top K Frequent Elements

Time Based Key Value Store

Remove All Adjacent Duplicates In String

Back to AppleLeetCode Index

Apple — 90 Days

Lru Cache

Rotate Array

Merge Intervals

Valid Palindrome

Top K Frequent Elements

Design Hit Counter

Two Sum

Maximum Subarray

Reverse Linked List

Remove All Adjacent Duplicates In String

Valid Parentheses

Merge K Sorted Lists

Find First And Last Position Of Element In Sorted Array

Valid Sudoku

Rotate Image

Group Anagrams

Spiral Matrix

Best Time To Buy And Sell Stock

Best Time To Buy And Sell Stock Ii

Number Of Islands

Course Schedule

Course Schedule Ii

Design Add And Search Words Data Structure

Serialize And Deserialize Binary Tree

Intersection Of Two Arrays

Decode String

Middle Of The Linked List

Time Based Key Value Store

Maximum Path Quality Of A Graph

Longest Substring Without Repeating Characters

Remove Duplicates From Sorted Array

Implement Trie Prefix Tree

Basic Calculator Ii

Implement Queue Using Stacks

Lowest Common Ancestor Of A Binary Tree

Product Of Array Except Self

Move Zeroes

Find Median From Data Stream

Design Hashmap

Best Time To Buy And Sell Stock With Transaction Fee

Short Encoding Of Words

Distribute Money To Maximum Children

Minimize Maximum Component Cost

Back to AppleLeetCode Index

Apple — 180 Days

Lru Cache

Rotate Array

Merge Intervals

Best Time To Buy And Sell Stock

Top K Frequent Elements

Best Time To Buy And Sell Stock Ii

Design Hit Counter

Valid Palindrome

Number Of Islands

Two Sum

Longest Common Prefix

Merge K Sorted Lists

Maximum Subarray

Reverse Linked List

Time Based Key Value Store

Valid Parentheses

Course Schedule Ii

Find First And Last Position Of Element In Sorted Array

Valid Sudoku

Rotate Image

Spiral Matrix

Course Schedule

Product Of Array Except Self

Find Median From Data Stream

Subarray Product Less Than K

Best Time To Buy And Sell Stock With Transaction Fee

Longest Substring Without Repeating Characters

Letter Combinations Of A Phone Number

Group Anagrams

Word Ladder

Min Stack

Implement Queue Using Stacks

Move Zeroes

Lfu Cache

Design Hashmap

Remove All Adjacent Duplicates In String

Remove Duplicates From Sorted Array

Trapping Rain Water

Longest Consecutive Sequence

Read N Characters Given Read4 Ii Call Multiple Times

Best Time To Buy And Sell Stock Iv

Design Add And Search Words Data Structure

Kth Largest Element In An Array

Basic Calculator Ii

Lowest Common Ancestor Of A Binary Tree

Alien Dictionary

Serialize And Deserialize Binary Tree

Flatten Nested List Iterator

Design Tic Tac Toe

Intersection Of Two Arrays

Insert Delete Getrandom O1

Decode String

String Compression

Middle Of The Linked List

Snapshot Array

Maximum Path Quality Of A Graph

Distribute Money To Maximum Children

Container With Most Water

Remove Nth Node From End Of List

Merge Two Sorted Lists

Permutations Ii

Set Matrix Zeroes

Word Search

Merge Sorted Array

Best Time To Buy And Sell Stock Iii

Word Ladder Ii

Read N Characters Given Read4

Find Peak Element

Binary Search Tree Iterator

Implement Trie Prefix Tree

Search A 2d Matrix Ii

Longest Substring With At Most K Distinct Characters

First Unique Character In A String

Design Circular Queue

Find K Closest Elements

Flood Fill

Short Encoding Of Words

Keys And Rooms

Maximize Distance To Closest Person

Exam Room

Rotting Oranges

Design Browser History

Minimize Maximum Component Cost

Back to AppleLeetCode Index

Google — LeetCode Plan

This page groups Google-focused practice plans.

Google — 30 Days

Problem List

Two Sum

Meeting Rooms Ii

Longest Common Prefix

Best Time To Buy And Sell Stock

Decode String

Add Two Numbers

Median Of Two Sorted Arrays

Palindrome Number

Find The Index Of The First Occurrence In A String

Longest Consecutive Sequence

Top K Frequent Elements

Number Of Visible People In A Queue

Longest Substring Without Repeating Characters

Roman To Integer

Next Permutation

Trapping Rain Water

Maximum Subarray

Binary Search

Longest Palindromic Substring

Container With Most Water

Valid Parentheses

Remove Element

Merge Intervals

Add Binary

Subarray Sum Equals K

Minimum Number Of Increments On Subarrays To Form A Target Array

Calculate Money In Leetcode Bank

Reverse Integer

3sum

Merge Two Sorted Lists

Remove Duplicates From Sorted Array

Find First And Last Position Of Element In Sorted Array

Majority Element

Second Highest Salary

Employees Earning More Than Their Managers

Longest Increasing Subsequence

Max Consecutive Ones

Middle Of The Linked List

Sort An Array

Next Greater Numerically Balanced Number

Add Two Integers

Make Array Elements Equal To Zero

Smallest Number With All Set Bits

Divide Two Integers

Search In Rotated Sorted Array

Powx N

Insert Interval

Unique Paths

Merge Sorted Array

Find Peak Element

Rotate Array

Reverse Linked List

Course Schedule

Contains Duplicate

Lowest Common Ancestor Of A Binary Tree

Delete Node In A Linked List

Valid Anagram

Move Zeroes

Split Array Largest Sum

Random Pick With Weight

Race Car

Final Value Of Variable After Performing Operations

Simple Bank System

Find Resultant Array After Removing Anagrams

Maximum Frequency Of An Element After Performing Operations I

Adjacent Increasing Subarrays Detection I

Generate Parentheses

Search Insert Position

Jump Game Ii

Spiral Matrix

Jump Game

Length Of Last Word

Rotate List

Sqrtx

Climbing Stairs

Sort Colors

Remove Duplicates From Sorted List

Largest Rectangle In Histogram

Binary Tree Inorder Traversal

Symmetric Tree

Binary Tree Level Order Traversal

Path Sum

Populating Next Right Pointers In Each Node

Valid Palindrome

Gas Station

Single Number

Linked List Cycle

Lru Cache

Find Minimum In Rotated Sorted Array Ii

Intersection Of Two Linked Lists

Two Sum Ii Input Array Is Sorted

Rank Scores

Happy Number

Remove Linked List Elements

Isomorphic Strings

Course Schedule Ii

Word Search Ii

Kth Largest Element In An Array

Maximal Square

Power Of Two

Nim Game

Increasing Triplet Subsequence

Nested List Weight Sum

Reverse String

Russian Doll Envelopes

Insert Delete Getrandom O1

Nth Digit

Remove K Digits

Third Maximum Number

Predict The Winner

Coin Change Ii

Single Element In A Sorted Array

Triangle Judgement

Longest Continuous Increasing Subsequence

Daily Temperatures

Guess The Word

Fruit Into Baskets

Rotting Oranges

Product Sales Analysis Iii

Greatest Common Divisor Of Strings

Shortest Path In Binary Matrix

The Earliest Moment When Everyone Become Friends

Path With Maximum Minimum Value

Find The Smallest Divisor Given A Threshold

Running Sum Of 1d Array

Avoid Flood In The City

Shortest Subarray To Be Removed To Make Array Sorted

All Ancestors Of A Node In A Directed Acyclic Graph

Count Unguarded Cells In The Grid

The Latest Time To Catch A Bus

Create Hello World Function

Taking Maximum Energy From The Mystic Dungeon

Adjacent Increasing Subarrays Detection Ii

Maximum Number Of Distinct Elements After Operations

Check If Digits Are Equal In String After Operations I

Back to GoogleLeetCode Index

Google — 90 Days

Two Sum

Longest Common Prefix

Add Two Numbers

Median Of Two Sorted Arrays

Palindrome Number

Trapping Rain Water

Best Time To Buy And Sell Stock

Longest Consecutive Sequence

3sum

Longest Substring Without Repeating Characters

Meeting Rooms Ii

Maximum Subarray

Subarray Sum Equals K

Longest Palindromic Substring

Container With Most Water

Merge Sorted Array

Decode String

Roman To Integer

Find The Index Of The First Occurrence In A String

Merge Intervals

Majority Element

Number Of Visible People In A Queue

Valid Parentheses

Search In Rotated Sorted Array

Top K Frequent Elements

Next Permutation

Single Number

Add Two Integers

Merge Two Sorted Lists

Generate Parentheses

Remove Duplicates From Sorted Array

Remove Element

Sort Colors

Find N Unique Integers Sum Up To Zero

Merge Strings Alternately

Create Hello World Function

Reverse Integer

Search Insert Position

Add Binary

Rotate Array

Move Zeroes

Binary Search

Recyclable And Low Fat Products

Spiral Matrix

Sqrtx

Lru Cache

Combine Two Tables

Happy Number

Reverse Linked List

Power Of Two

3sum Closest

Rotate Image

Group Anagrams

House Robber

Count Primes

Split Array Largest Sum

Regular Expression Matching

4sum

Jump Game Ii

N Queens

Insert Interval

Climbing Stairs

Second Highest Salary

Employees Earning More Than Their Managers

Rising Temperature

Kth Largest Element In An Array

Sliding Window Maximum

Longest Increasing Subsequence

Intersection Of Two Arrays

Find First And Last Position Of Element In Sorted Array

Sudoku Solver

Powx N

Maximal Square

Palindrome Linked List

Reverse String

Largest Triangle Area

Koko Eating Bananas

Sort An Array

Minimum Number Of Increments On Subarrays To Form A Target Array

Valid Sudoku

Wildcard Matching

Jump Game

Rotate List

Plus One

Edit Distance

Set Matrix Zeroes

Minimum Window Substring

Subsets Ii

Reverse Linked List Ii

Binary Tree Zigzag Level Order Traversal

Valid Palindrome

Candy

Linked List Cycle

Find Peak Element

Course Schedule

Contains Duplicate

Search A 2d Matrix Ii

Valid Anagram

Reverse Vowels Of A String

Logger Rate Limiter

Longest Repeating Character Replacement

Coin Change Ii

Single Element In A Sorted Array

Employee Bonus

24 Game

New 21 Game

Middle Of The Linked List

Fruit Into Baskets

Students And Examinations

Next Greater Numerically Balanced Number

Zigzag Conversion

Reverse Nodes In K Group

Unique Paths

Subsets

Largest Rectangle In Histogram

Pascals Triangle

Copy List With Random Pointer

Maximum Product Subarray

Number Of Islands

Remove Linked List Elements

Course Schedule Ii

Product Of Array Except Self

Ugly Number

Find The Duplicate Number

Power Of Three

Russian Doll Envelopes

Insert Delete Getrandom O1

Remove K Digits

Third Maximum Number

Pacific Atlantic Water Flow

Find All Numbers Disappeared In An Array

Max Consecutive Ones

Next Greater Element I

Diagonal Traverse

Random Pick With Weight

Find Customer Referee

Daily Temperatures

Rotate String

Peak Index In A Mountain Array

Rotting Oranges

Longest Common Subsequence

Count Submatrices With All Ones

Water Bottles

Calculate Money In Leetcode Bank

Maximum Number Of Words You Can Type

Largest 3 Same Digit Number In String

Minimum Operations To Make The Integer Zero

Find The Minimum Area To Cover All Ones I

Design Task Manager

Apply Substitutions

Letter Combinations Of A Phone Number

Remove Nth Node From End Of List

Divide Two Integers

First Missing Positive

Length Of Last Word

Text Justification

Same Tree

Binary Tree Level Order Traversal

Best Time To Buy And Sell Stock Ii

Word Ladder

Surrounded Regions

Gas Station

Reverse Words In A String

Min Stack

Intersection Of Two Linked Lists

Compare Version Numbers

Isomorphic Strings

Shortest Palindrome

Basic Calculator

Implement Stack Using Queues

Kth Smallest Element In A Bst

Lowest Common Ancestor Of A Binary Tree

Delete Node In A Linked List

Perfect Squares

Odd Even Linked List

Power Of Four

Find The Difference

Fizz Buzz

Partition Equal Subset Sum

Target Sum

Triangle Judgement

Maximum Average Subarray I

Valid Parenthesis String

Top K Frequent Words

Range Module

Soup Servings

Reordered Power Of 2

Binary Subarrays With Sum

Squares Of A Sorted Array

Longest Duplicate Substring

The Earliest Moment When Everyone Become Friends

Convert Integer To The Sum Of Two No Zero Integers

Maximum 69 Number

Running Sum Of 1d Array

Longest Subarray Of 1s After Deleting One Element

Average Time Of Process Per Machine

Invalid Tweets

Check If Array Is Sorted And Rotated

Concatenation Of Array

Final Value Of Variable After Performing Operations

Find Resultant Array After Removing Anagrams

Find The Maximum Achievable Number

Make Array Elements Equal To Zero

Smallest Number With All Set Bits

Minimum Operations To Make Array Elements Zero

Inverse Coin Change

String To Integer Atoi

Integer To Roman

Merge K Sorted Lists

Multiply Strings

Search A 2d Matrix

Remove Duplicates From Sorted Array Ii

Remove Duplicates From Sorted List

Binary Tree Inorder Traversal

Interleaving String

Recover Binary Search Tree

Symmetric Tree

Construct Binary Tree From Preorder And Inorder Traversal

Minimum Depth Of Binary Tree

Populating Next Right Pointers In Each Node

Triangle

Palindrome Partitioning

Palindrome Partitioning Ii

Word Break

Linked List Cycle Ii

Reorder List

Max Points On A Line

Find Minimum In Rotated Sorted Array Ii

Two Sum Ii Input Array Is Sorted

Rank Scores

Number Of 1 Bits

House Robber Ii

Invert Binary Tree

Summary Ranges

Implement Queue Using Stacks

Binary Tree Paths

Add Digits

Integer To English Words

First Bad Version

Find Median From Data Stream

Serialize And Deserialize Binary Tree

Range Sum Query 2d Immutable

Increasing Triplet Subsequence

Counting Bits

Largest Divisible Subset

Ransom Note

Trapping Rain Water Ii

Assign Cookies

132 Pattern

Fibonacci Number

Detect Capital

Longest Word In Dictionary Through Deleting

Number Of Provinces

Game Play Analysis Iv

Big Countries

Palindromic Substrings

Longest Continuous Increasing Subsequence

Design Linked List

Jewels And Stones

Swim In Rising Water

Race Car

Guess The Word

Sum Of Subarray Minimums

Vowel Spellchecker

Largest Perimeter Triangle

Max Consecutive Ones Iii

Capacity To Ship Packages Within D Days

Greatest Common Divisor Of Strings

Shortest Path In Binary Matrix

Car Pooling

Path With Maximum Minimum Value

Article Views I

Immediate Food Delivery Ii

Average Selling Price

Search Suggestions System

Count Square Submatrices With All Ones

Find The Smallest Divisor Given A Threshold

Avoid Flood In The City

Kth Missing Positive Number

Magnetic Force Between Two Balls

Minimum Number Of People To Teach

Check If The Sentence Is Pangram

Minimum Interval To Include Each Query

Number Of Ways To Arrive At Destination

Simple Bank System

Rearrange Array Elements By Sign

Number Of People Aware Of A Secret

The Latest Time To Catch A Bus

Counter

Maximum Total Damage With Spell Casting

Maximum Frequency Of An Element After Performing Operations I

Adjacent Increasing Subarrays Detection I

Maximum Number Of Distinct Elements After Operations

Next Special Palindrome Number

Permutations

N Queens Ii

Permutation Sequence

Word Search

Remove Duplicates From Sorted List Ii

Maximal Rectangle

Unique Binary Search Trees Ii

Unique Binary Search Trees

Maximum Depth Of Binary Tree

Convert Sorted Array To Binary Search Tree

Balanced Binary Tree

Path Sum

Distinct Subsequences

Binary Tree Maximum Path Sum

Sum Root To Leaf Numbers

Sort List

Evaluate Reverse Polish Notation

Maximum Gap

Fraction To Recurring Decimal

Excel Sheet Column Title

Nth Highest Salary

Largest Number

Duplicate Emails

Delete Duplicate Emails

Word Search Ii

Contains Duplicate Ii

Majority Element Ii

Group Shifted Strings

Meeting Rooms

Paint House

Missing Number

Encode And Decode Strings

Expression Add Operators

Word Pattern

Nim Game

Range Sum Query Mutable

Best Time To Buy And Sell Stock With Cooldown

Burst Balloons

Coin Change

Wiggle Sort Ii

Longest Increasing Path In A Matrix

Nested List Weight Sum

Flatten Nested List Iterator

Intersection Of Two Arrays Ii

Sum Of Two Integers

First Unique Character In A String

Is Subsequence

Evaluate Division

Nth Digit

Frog Jump

Queue Reconstruction By Height

String Compression

Sort Characters By Frequency

Lfu Cache

Implement Rand10 Using Rand7

Sliding Window Median

Predict The Winner

Reverse Pairs

Continuous Subarray Sum

Minimum Absolute Difference In Bst

Encode And Decode Tinyurl

Reverse String Ii

Remove Boxes

Permutation In String

Managers With At Least 5 Direct Reports

Classes With At Least 5 Students

Friend Requests Ii Who Has The Most Friends

Can Place Flowers

Merge Two Binary Trees

Design Circular Queue

Exchange Seats

Sum Of Square Numbers

Exclusive Time Of Functions

Design Search Autocomplete System

Find Duplicate Subtrees

Valid Palindrome Ii

Baseball Game

Redundant Connection

Repeated String Match

Binary Number With Alternating Bits

Degree Of An Array

Subarray Product Less Than K

Accounts Merge

Find Pivot Index

Flood Fill

Asteroid Collision

Employee Free Time

Reorganize String

Number Of Matching Subsequences

Find And Replace In String

Shortest Path Visiting All Nodes

Exam Room

All Nodes Distance K In Binary Tree

Transpose Matrix

Minimum Number Of Refueling Stops

Online Stock Span

X Of A Kind In A Deck Of Cards

Unique Email Addresses

Minimum Falling Path Sum

Maximum Width Ramp

Minimum Area Rectangle Ii

K Closest Points To Origin

Time Based Key Value Store

Satisfiability Of Equality Equations

Remove Outermost Parentheses

Divisor Game

Longest String Chain

Last Stone Weight Ii

Product Sales Analysis Iii

Shortest Common Supersequence

Defanging An Ip Address

Delete Nodes And Return Forest

Highest Grade For Each Student

Snapshot Array

Critical Connections In A Network

Monthly Transactions I

Last Person To Fit In The Bus

Minimum Moves To Move A Box To Their Target Location

Delete Leaves With A Given Value

Maximum Number Of Events That Can Be Attended

Maximum Sum Bst In Binary Tree

Minimum Number Of Days To Make M Bouquets

Xor Operation In An Array

Shortest Subarray To Be Removed To Make Array Sorted

Remove Max Number Of Edges To Keep Graph Fully Traversable

Min Cost To Connect All Points

Percentage Of Users Attended A Contest

Lowest Common Ancestor Of A Binary Tree Iii

Defuse The Bomb

Number Of Students Unable To Eat Lunch

Maximum Units On A Truck

Find The Highest Altitude

Check If Number Is A Sum Of Powers Of Three

Maximum Average Pass Ratio

Frequency Of The Most Frequent Element

Find A Peak Element Ii

Confirmation Rate

Three Divisors

Reverse Prefix Of Word

All Ancestors Of A Node In A Directed Acyclic Graph

Replace Non Coprime Numbers In Array

Maximum Score Of A Node Sequence

Count Unguarded Cells In The Grid

Decode The Message

Number Of Zero Filled Subarrays

Design A Food Rating System

Meeting Rooms Iii

Range Product Queries Of Powers

Left And Right Sum Differences

Collect Coins In A Tree

Minimize The Maximum Difference Of Pairs

Ways To Express An Integer As Sum Of Powers

Find Missing And Repeated Values

Find Beautiful Indices In The Given Array I

Find The Number Of Ways To Place People I

Taking Maximum Energy From The Mystic Dungeon

Clear Digits

Maximum Frequency Of An Element After Performing Operations Ii

Adjacent Increasing Subarrays Detection Ii

Maximum Subarray With Equal Products

Sort Matrix By Diagonals

Check If Digits Are Equal In String After Operations I

Design Spreadsheet

Minimum Pair Removal To Sort Array I

Find Closest Person

Partition Array Into K Distinct Groups

Count Bowl Subarrays

Subsequence Sum After Capping Elements

Number Of Stable Subsequences

Sum Of Perfect Square Ancestors

Lexicographically Smallest Permutation Greater Than Target

Back to GoogleLeetCode Index

Google — 180 Days

Two Sum

Add Two Numbers

Longest Common Prefix

Median Of Two Sorted Arrays

Palindrome Number

Trapping Rain Water

Best Time To Buy And Sell Stock

Longest Substring Without Repeating Characters

3sum

Longest Consecutive Sequence

Count Number Of Trapezoids Ii

Longest Palindromic Substring

Count Number Of Trapezoids I

Roman To Integer

Merge Intervals

Container With Most Water

Subarray Sum Equals K

Maximum Subarray

Valid Parentheses

Meeting Rooms Ii

Number Of Visible People In A Queue

Next Permutation

Merge Two Sorted Lists

Merge Sorted Array

Majority Element

Remove Duplicates From Sorted Array

Pascals Triangle

Decode String

Search In Rotated Sorted Array

Reverse Integer

Single Number

Generate Parentheses

N Queens

Top K Frequent Elements

Sort Colors

Add Two Integers

Climbing Stairs

Move Zeroes

Find The Index Of The First Occurrence In A String

Sliding Window Maximum

4sum

Spiral Matrix

Set Matrix Zeroes

Number Of Islands

Valid Anagram

Recyclable And Low Fat Products

Merge Strings Alternately

Jump Game

Happy Number

Reverse Linked List

Power Of Two

Search Insert Position

Rotate Image

Add Binary

Split Array Largest Sum

Binary Search

Remove Element

Subsets

Find Peak Element

Create Hello World Function

Group Anagrams

Largest Rectangle In Histogram

Rotate Array

Koko Eating Bananas

Regular Expression Matching

Valid Sudoku

Subsets Ii

Candy

Longest Repeating Character Replacement

Zigzag Conversion

3sum Closest

Unique Paths

Count Primes

Maximal Square

Best Time To Buy And Sell Stock Ii

Lru Cache

House Robber

Powx N

Linked List Cycle

Min Stack

Combine Two Tables

Basic Calculator

Longest Increasing Subsequence

Russian Doll Envelopes

Single Element In A Sorted Array

Letter Combinations Of A Phone Number

Remove Nth Node From End Of List

Find First And Last Position Of Element In Sorted Array

Sqrtx

Maximal Rectangle

Valid Palindrome

Reverse Words In A String

Maximum Product Subarray

Second Highest Salary

Kth Largest Element In An Array

Contains Duplicate

Rotate List

Partition Equal Subset Sum

Max Consecutive Ones

Next Greater Element I

Next Special Palindrome Number

Minimum Window Substring

Product Of Array Except Self

Top K Frequent Words

Fruit Into Baskets

Sum Of Subarray Minimums

Merge K Sorted Lists

Reverse Nodes In K Group

Divide Two Integers

Sudoku Solver

Jump Game Ii

Plus One

Binary Tree Maximum Path Sum

Palindrome Partitioning

Word Break

Sort List

Two Sum Ii Input Array Is Sorted

Intersection Of Two Arrays

Logger Rate Limiter

Peak Index In A Mountain Array

Middle Of The Linked List

Squares Of A Sorted Array

Longest Duplicate Substring

Inverse Coin Change

First Missing Positive

Wildcard Matching

Insert Interval

Text Justification

Edit Distance

Same Tree

Binary Tree Zigzag Level Order Traversal

Reorder List

Employees Earning More Than Their Managers

Rising Temperature

Course Schedule

Target Sum

Fibonacci Number

Employee Bonus

Task Scheduler

Sort An Array

Path With Maximum Minimum Value

Article Views I

Find N Unique Integers Sum Up To Zero

Apply Substitutions

Remove Duplicates From Sorted List

Copy List With Random Pointer

Isomorphic Strings

Palindrome Linked List

Lowest Common Ancestor Of A Binary Tree

Insert Delete Getrandom O1

K Th Smallest In Lexicographical Order

Diagonal Traverse

Diameter Of Binary Tree

Range Module

Rotting Oranges

Maximum Number Of Events That Can Be Attended

Maximize Subarray Gcd Score

Partition String

Permutations

Word Search

Contains Duplicate Ii

Delete Node In A Linked List

Find The Duplicate Number

Reverse String

Remove K Digits

Lfu Cache

Reverse Pairs

Coin Change Ii

Number Of Provinces

Daily Temperatures

Rotate String

Running Sum Of 1d Array

Rearrange Array Elements By Sign

Fruits Into Baskets Ii

String To Integer Atoi

Integer To Roman

Symmetric Tree

Single Number Ii

Find Minimum In Rotated Sorted Array

Intersection Of Two Linked Lists

Remove Linked List Elements

House Robber Ii

Kth Smallest Element In A Bst

Perfect Squares

Coin Change

Odd Even Linked List

Reverse Vowels Of A String

Is Subsequence

String Compression

Find All Numbers Disappeared In An Array

Random Pick With Weight

Longest Harmonious Subsequence

24 Game

Soup Servings

New 21 Game

Reordered Power Of 2

Max Consecutive Ones Iii

Delete Nodes And Return Forest

Shortest Path In A Grid With Obstacles Elimination

Check If Array Is Sorted And Rotated

Meeting Rooms Iii

Separate Squares I

Length Of Last Word

Minimum Path Sum

Remove Duplicates From Sorted List Ii

Reverse Linked List Ii

Binary Tree Level Order Traversal

Construct Binary Tree From Preorder And Inorder Traversal

Triangle

Surrounded Regions

Linked List Cycle Ii

Binary Tree Right Side View

Implement Trie Prefix Tree

First Bad Version

Serialize And Deserialize Binary Tree

Power Of Three

Fizz Buzz

Third Maximum Number

Pacific Atlantic Water Flow

Largest Triangle Area

Capacity To Ship Packages Within D Days

Longest Common Subsequence

Count Square Submatrices With All Ones

Students And Examinations

Minimum Number Of Days To Make M Bouquets

Minimum Number Of Increments On Subarrays To Form A Target Array

Maximum Erasure Value

Minimum Time To Finish The Race

Rearranging Fruits

Find Missing And Repeated Values

Type Of Triangle

Substring With Concatenation Of All Words

Multiply Strings

Search A 2d Matrix

Remove Duplicates From Sorted Array Ii

Recover Binary Search Tree

Convert Sorted Array To Binary Search Tree

Course Schedule Ii

Shortest Palindrome

Implement Stack Using Queues

Implement Queue Using Stacks

Search A 2d Matrix Ii

Expression Add Operators

Intersection Of Two Arrays Ii

Largest Divisible Subset

Non Overlapping Intervals

Assign Cookies

Managers With At Least 5 Direct Reports

Find Customer Referee

Big Countries

Triangle Judgement

Palindromic Substrings

Max Area Of Island

Swim In Rising Water

Guess The Word

Binary Subarrays With Sum

Vertical Order Traversal Of A Binary Tree

Replace Employee Id With The Unique Identifier

Longest Subarray Of 1s After Deleting One Element

Kth Missing Positive Number

Calculate Money In Leetcode Bank

Maximum Score From Removing Substrings

Concatenation Of Array

Next Greater Numerically Balanced Number

Minimize The Maximum Difference Of Pairs

Distribute Candies Among Children Ii

Find The Minimum Area To Cover All Ones I

Find The K Th Character In String Game I

Minimum Increments To Equalize Leaf Paths

Permutation Sequence

Binary Tree Inorder Traversal

Maximum Depth Of Binary Tree

Word Ladder

Gas Station

Max Points On A Line

Evaluate Reverse Polish Notation

Find Minimum In Rotated Sorted Array Ii

Excel Sheet Column Title

Consecutive Numbers

Duplicate Emails

Customers Who Never Order

Design Add And Search Words Data Structure

Word Search Ii

Invert Binary Tree

Add Digits

Ugly Number

Missing Number

Find Median From Data Stream

Burst Balloons

Increasing Triplet Subsequence

Counting Bits

Find Leaves Of Binary Tree

Sum Of Two Integers

First Unique Character In A String

Find The Difference

Add Strings

Find All Duplicates In An Array

132 Pattern

Repeated Substring Pattern

Sliding Window Median

Permutation In String

Can Place Flowers

Exchange Seats

Maximum Average Subarray I

Find K Closest Elements

Maximum Swap

Valid Parenthesis String

Valid Palindrome Ii

Design Linked List

Flood Fill

Jewels And Stones

Transpose Matrix

Bitwise Ors Of Subarrays

Snakes And Ladders

Minimum Falling Path Sum

Minimum Number Of K Consecutive Bit Flips

Longest String Chain

Greatest Common Divisor Of Strings

Shortest Path In Binary Matrix

Shortest Common Supersequence

Snapshot Array

Search Suggestions System

Paint House Iii

Count Submatrices With All Ones

Invalid Tweets

Single Threaded Cpu

Frequency Of The Most Frequent Element

Count Good Numbers

Kth Smallest Product Of Two Sorted Arrays

Find All K Distant Indices In An Array

Largest 3 Same Digit Number In String

The Latest Time To Catch A Bus

Number Of Common Factors

Range Product Queries Of Powers

Minimum Operations To Make The Integer Zero

Create A Dataframe From List

Divide Array Into Arrays With Max Difference

Find The Original Typed String I

Find The Original Typed String Ii

Design Task Manager

Swap Nodes In Pairs

Combination Sum

Valid Number

Combinations

Search In Rotated Sorted Array Ii

Decode Ways

Interleaving String

Distinct Subsequences

Best Time To Buy And Sell Stock Iii

Rank Scores

Largest Number

Number Of 1 Bits

Bitwise And Of Numbers Range

Minimum Size Subarray Sum

Basic Calculator Ii

Encode And Decode Strings

Integer To English Words

Range Sum Query Immutable

Range Sum Query 2d Immutable

Additive Number

Best Time To Buy And Sell Stock With Cooldown

Find K Pairs With Smallest Sums

Ransom Note

Lexicographical Numbers

Nth Digit

Frog Jump

Path Sum Iii

Next Greater Element Ii

Detect Capital

Contiguous Array

Game Play Analysis Iv

Valid Triangle Number

Design Circular Queue

Repeated String Match

Is Graph Bipartite

Cheapest Flights Within K Stops

Find And Replace In String

Shortest Path Visiting All Nodes

Boats To Save People

Online Stock Span

Car Pooling

The Earliest Moment When Everyone Become Friends

Monthly Transactions I

Unique Number Of Occurrences

Count Number Of Nice Subarrays

Find The Smallest Divisor Given A Threshold

Convert Integer To The Sum Of Two No Zero Integers

Maximum 69 Number

Minimum Number Of Taps To Open To Water A Garden

Find Lucky Integer In An Array

Water Bottles

Average Time Of Process Per Machine

Maximum Number Of Events That Can Be Attended Ii

Check If The Sentence Is Pangram

Painting A Grid With Three Different Colors

Maximum Number Of Words You Can Type

Delete Characters To Make Fancy String

Sum Of K Mirror Numbers

Find Subsequence Of Length K With The Largest Sum

Count Hills And Valleys In An Array

Number Of People Aware Of A Secret

Move Pieces To Obtain A String

Smallest Subarrays With Maximum Bitwise Or

Counter

Find The Maximum Achievable Number

Find The Maximum Length Of Valid Subsequence I

Zero Array Transformation I

Fruits Into Baskets Iii

Maximize Subarrays After Removing One Conflicting Pair

Minimum Operations To Make Array Elements Zero

Longest Valid Parentheses

Combination Sum Ii

N Queens Ii

Spiral Matrix Ii

Unique Paths Ii

Simplify Path

Balanced Binary Tree

Minimum Depth Of Binary Tree

Flatten Binary Tree To Linked List

Populating Next Right Pointers In Each Node

Pascals Triangle Ii

Word Ladder Ii

Sum Root To Leaf Numbers

Palindrome Partitioning Ii

Maximum Gap

Compare Version Numbers

Nth Highest Salary

Repeated Dna Sequences

Combination Sum Iii

The Skyline Problem

Summary Ranges

Majority Element Ii

Different Ways To Add Parentheses

Meeting Rooms

Binary Tree Paths

H Index

Power Of Four

Water And Jug Problem

Trapping Rain Water Ii

Find All Anagrams In A String

Sort Characters By Frequency

Continuous Subarray Sum

Minimum Absolute Difference In Bst

Minimum Time Difference

Next Greater Element Iii

Sum Of Square Numbers

Design Search Autocomplete System

Two Sum Iv Input Is A Bst

Longest Continuous Increasing Subsequence

Baseball Game

Accounts Merge

Find Pivot Index

Asteroid Collision

Network Delay Time

Swap Adjacent In Lr String

Number Of Matching Subsequences

Race Car

Minimum Area Rectangle Ii

K Closest Points To Origin

Time Based Key Value Store

Remove Outermost Parentheses

Divisor Game

Project Employees I

Defanging An Ip Address

Relative Sort Array

Smallest String With Swaps

Average Selling Price

Number Of Closed Islands

Convert Binary Number In A Linked List To Integer

Maximum Sum Bst In Binary Tree

Maximum Points You Can Obtain From Cards

Number Of Good Pairs

Three Consecutive Odds

The Number Of Employees Which Report To Each Employee

Minimum Interval To Include Each Query

Confirmation Rate

Final Value Of Variable After Performing Operations

Longest Subsequence Repeated K Times

Maximum Difference Between Increasing Elements

Delete The Middle Node Of A Linked List

Detonate The Maximum Bombs

Maximum Fruits Harvested After At Most K Steps

Minimum Weighted Subgraph With The Required Paths

Find Resultant Array After Removing Anagrams

Remove Nodes From Linked List

Sleep

Ways To Express An Integer As Sum Of Powers

Find Words Containing Character

Valid Word

Maximum Frequency Of An Element After Performing Operations I

Make Array Elements Equal To Zero

Smallest Number With All Set Bits

Maximize The Number Of Target Nodes After Connecting Trees Ii

Reschedule Meetings For Maximum Free Time I

Sort Matrix By Diagonals

Minimum Pair Removal To Sort Array I

Count And Say

Permutations Ii

Restore Ip Addresses

Unique Binary Search Trees Ii

Path Sum

Clone Graph

Word Break Ii

Binary Tree Preorder Traversal

Fraction To Recurring Decimal

Factorial Trailing Zeroes

Department Highest Salary

Best Time To Buy And Sell Stock Iv

Count Complete Tree Nodes

Number Of Digit One

Lowest Common Ancestor Of A Binary Search Tree

Group Shifted Strings

Nim Game

Minimum Height Trees

Remove Duplicate Letters

Longest Increasing Path In A Matrix

Flatten Nested List Iterator

Count Numbers With Unique Digits

Combination Sum Iv

Kth Smallest Element In A Sorted Matrix

Shuffle An Array

Evaluate Division

Queue Reconstruction By Height

Reconstruct Original Digits From English

Construct Quad Tree

Sequence Reconstruction

Delete Node In A Bst

Longest Word In Dictionary Through Deleting

Reverse String Ii

01 Matrix

Array Partition

Shortest Unsorted Continuous Subarray

Delete Operation For Two Strings

Investments In 2016

Classes With At Least 5 Students

Smallest Range Covering Elements From K Lists

Exclusive Time Of Functions

Maximum Width Of Binary Tree

Degree Of An Array

Subarray Product Less Than K

Best Time To Buy And Sell Stock With Transaction Fee

Find Smallest Letter Greater Than Target

Min Cost Climbing Stairs

Employee Free Time

Reorganize String

Find Eventual Safe States

Bus Routes

Maximize Distance To Closest Person

Exam Room

Lemonade Change

X Of A Kind In A Deck Of Cards

Sort Array By Parity Ii

Reveal Cards In Increasing Order

Vowel Spellchecker

Odd Even Jump

Largest Perimeter Triangle

Subarrays With K Different Integers

Customers Who Bought All Products

Last Stone Weight

Last Stone Weight Ii

Parsing A Boolean Expression

Maximum Nesting Depth Of Two Valid Parentheses Strings

Product Price At A Given Date

Immediate Food Delivery Ii

Last Person To Fit In The Bus

Queries Quality And Percentage

Remove Sub Folders From The Filesystem

Subtract The Product And Sum Of Digits Of An Integer

Find The City With The Smallest Number Of Neighbors At A Threshold Distance

Maximum Students Taking Exam

Time Needed To Inform All Employees

Avoid Flood In The City

Number Of Subsequences That Satisfy The Given Sum Condition

Get The Maximum Score

Minimum Cost To Cut A Stick

Magnetic Force Between Two Balls

Min Cost To Connect All Points

Lowest Common Ancestor Of A Binary Tree Iii

Defuse The Bomb

Richest Customer Wealth

Max Number Of K Sum Pairs

Sum Of Absolute Differences In A Sorted Array

Number Of Students Unable To Eat Lunch

Maximum Units On A Truck

Find The Highest Altitude

Minimum Number Of People To Teach

Minimum Number Of Operations To Move All Balls To Each Box

Car Fleet Ii

Sum Of Beauty Of All Substrings

Maximum Population Year

Finding Pairs With A Certain Sum

The Earliest And Latest Rounds Where Players Compete

Find A Peak Element Ii

Largest Odd Number In String

Three Divisors

Find If Path Exists In Graph

Number Of Ways To Arrive At Destination

Partition Array Into Two Arrays To Minimize Sum Difference

Simple Bank System

Count Number Of Maximum Bitwise Or Subsets

Step By Step Directions From A Binary Tree Node To Another

Sum Of Subarray Ranges

Maximum Twin Sum Of A Linked List

Maximum Candies Allocated To K Children

Maximum Score Of A Node Sequence

Find Closest Node To Given Two Nodes

Maximum Subsequence Score

Left And Right Sum Differences

Array Prototype Last

To Be Or Not To Be

Add Two Promises

Divisible And Non Divisible Sums Difference

Find Beautiful Indices In The Given Array I

Alice And Bob Playing Flower Game

Find The Number Of Ways To Place People I

Score Of A String

Lexicographically Minimum String After Removing Stars

Clear Digits

Maximum Total Damage With Spell Casting

Find The Maximum Length Of Valid Subsequence Ii

Delete Nodes From Linked List Present In Array

Vowels Game In A String

Adjacent Increasing Subarrays Detection I

Maximum Number Of Distinct Elements After Operations

Maximum Difference Between Adjacent Elements In A Circular Array

Reschedule Meetings For Maximum Free Time Ii

Maximum Difference Between Even And Odd Frequency I

Maximum Difference Between Even And Odd Frequency Ii

Path Existence Queries In A Graph I

Maximum Product Of Two Digits

Minimum Swaps To Sort By Digit Sum

Find Weighted Median Node In Tree

Partition List

Scramble String

Gray Code

Unique Binary Search Trees

Validate Binary Search Tree

Construct Binary Tree From Inorder And Postorder Traversal

Binary Tree Level Order Traversal Ii

Convert Sorted List To Binary Search Tree

Populating Next Right Pointers In Each Node Ii

Insertion Sort List

Excel Sheet Column Number

Binary Search Tree Iterator

Dungeon Game

Valid Phone Numbers

Delete Duplicate Emails

Rectangle Area

Paint House

Single Number Iii

Graph Valid Tree

Trips And Users

Word Pattern

Smallest Rectangle Enclosing Black Pixels

Number Of Islands Ii

Range Sum Query Mutable

Binary Tree Vertical Order Traversal

Maximum Product Of Word Lengths

Create Maximum Number

Wiggle Sort Ii

Patching Array

House Robber Iii

Nested List Weight Sum

Integer Break

Android Unlock Patterns

Design Twitter

Design Hit Counter

Super Pow

Linked List Random Node

Longest Absolute File Path

Rotate Function

Valid Word Abbreviation

Arithmetic Slices

Maximum Xor Of Two Numbers In An Array

Flatten A Multilevel Doubly Linked List

All Oone Data Structure

Minimum Genetic Mutation

Number Of Segments In A String

Arranging Coins

Serialize And Deserialize Bst

Minimum Moves To Equal Array Elements

Can I Win

Count The Repetitions

Implement Rand10 Using Rand7

Number Complement

Predict The Winner

Robot Room Cleaner

Game Play Analysis I

Longest Palindromic Subsequence

Encode And Decode Tinyurl

Remove Boxes

Student Attendance Record I

Student Attendance Record Ii

Reverse Words In A String Iii

Distribute Candies

Friend Requests Ii Who Has The Most Friends

Merge Two Binary Trees

Solve The Equation

Set Mismatch

Replace Words

2 Keys Keyboard

Find Duplicate Subtrees

Robot Return To Origin

Non Decreasing Array

Number Of Longest Increasing Subsequence

Redundant Connection

Redundant Connection Ii

Maximum Sum Of 3 Non Overlapping Subarrays

Binary Number With Alternating Bits

Search In A Binary Search Tree

Design Hashset

Design Hashmap

Maximum Length Of Repeated Subarray

Candy Crush

My Calendar I

Sentence Similarity Ii

Open The Lock

Cracking The Safe

Basic Calculator Iii

Domino And Tromino Tiling

Split Array With Same Average

Expressive Words

Subdomain Visit Count

Most Common Word

Most Profit Assigning Work

Making A Large Island

Flipping An Image

Sum Of Distances In Tree

Backspace String Compare

Hand Of Straights

Car Fleet

All Nodes Distance K In Binary Tree

Minimum Number Of Refueling Stops

Stone Game

Spiral Matrix Iii

All Possible Full Binary Trees

Sort Array By Parity

Maximum Sum Circular Subarray

Minimum Add To Make Parentheses Valid

Unique Email Addresses

Number Of Recent Calls

Shortest Bridge

Regions Cut By Slashes

Maximum Width Ramp

Subarray Sums Divisible By K

Unique Paths Iii

String Without Aaa Or Bbb

Interval List Intersections

Add To Array Form Of Integer

Satisfiability Of Equality Equations

Cousins In Binary Tree

Number Of Squareful Arrays

Find The Town Judge

Pairs Of Songs With Total Durations Divisible By 60

Number Of Enclaves

Robot Bounded In Circle

Partition Array For Maximum Sum

Lexicographically Smallest Equivalent String

Longest Repeating Substring

Product Sales Analysis Iii

Corporate Flight Bookings

Highest Grade For Each Student

Print Zero Even Odd

Minimum Cost Tree From Leaf Values

Critical Connections In A Network

Minimum Knight Moves

Path With Maximum Gold

Tiling A Rectangle With The Fewest Squares

Minimum Moves To Move A Box To Their Target Location

Remove Interval

Maximum Candies You Can Get From Boxes

Decompress Run Length Encoded List

Delete Leaves With A Given Value

Rank Transform Of An Array

Movie Rating

Number Of Steps To Reduce A Number To Zero

Jump Game Iv

Number Of Substrings Containing All Three Characters

Minimum Cost To Make At Least One Valid Path In A Grid

Generate A String With Characters That Have Odd Counts

Design A Stack With Increment Operation

Maximum Performance Of A Team

Design Underground System

Stone Game Iii

Minimum Value To Get Positive Step By Step Sum

Build Array Where You Can Find The Maximum Exactly K Comparisons

Kids With The Greatest Number Of Candies

Maximum Number Of Vowels In A Substring Of Given Length

Maximum Product Of Two Elements In An Array

Reorder Routes To Make All Paths Lead To The City Zero

Xor Operation In An Array

Path Crossing

Count Odd Numbers In An Interval Range

Shuffle String

Shortest Subarray To Be Removed To Make Array Sorted

Remove Max Number Of Edges To Keep Graph Fully Traversable

Customer Who Visited But Did Not Make Any Transactions

Path With Minimum Effort

Rank Transform Of A Matrix

Percentage Of Users Attended A Contest

Minimum Operations To Reduce X To Zero

Fix Names In A Table

Maximum Repeating Substring

Merge In Between Linked Lists

Ways To Split Array Into Three Subarrays

Swapping Nodes In A Linked List

Check If Number Is A Sum Of Powers Of Three

Primary Department For Each Employee

Find Center Of Star Graph

Maximum Average Pass Ratio

Maximum Value At A Given Index In A Bounded Array

Sorting The Sentence

Rotating The Box

Determine Whether Matrix Can Be Obtained By Rotation

Build Array From Permutation

Unique Length 3 Palindromic Subsequences

Delete Duplicate Folders In System

Find Greatest Common Divisor Of Array

Count Special Quadruplets

Reverse Prefix Of Word

Maximum Product Of The Length Of Two Palindromic Subsequences

Detect Squares

Maximize The Confusion Of An Exam

Maximum Number Of Words Found In Sentences

Find All Possible Recipes From Given Supplies

Longest Palindrome By Concatenating Two Letter Words

All Ancestors Of A Node In A Directed Acyclic Graph

Replace Non Coprime Numbers In Array

Largest Number After Digit Swaps By Parity

Number Of Flowers In Full Bloom

Count Unguarded Cells In The Grid

Escape The Spreading Fire

Count Integers In Intervals

Partition Array Such That Maximum Difference Is K

Successful Pairs Of Spells And Potions

Minimum Score After Removals On A Tree

Decode The Message

Number Of Zero Filled Subarrays

Design A Food Rating System

Number Of Unique Subjects Taught By Each Teacher

Task Scheduler Ii

Minimum Replacements To Sort The Array

Minimum Recolors To Get K Consecutive Black Blocks

Longest Nice Subarray

Maximum Matching Of Players With Trainers

Longest Subarray With Maximum Bitwise And

Height Of Binary Tree After Subtree Removal Queries

Closest Nodes Queries In A Binary Search Tree

Minimum Score Of A Path Between Two Cities

Time Taken To Cross The Door

House Robber Iv

Collect Coins In A Tree

Return Length Of Arguments Passed

Minimize String Length

Continuous Subarrays

Minimum Equal Sum Of Two Arrays After Replacing Zeros

Find Common Elements Between Two Arrays

Maximum Area Of Longest Diagonal Rectangle

Count Elements With Maximum Frequency

Minimum Deletions To Make String K Special

Taking Maximum Energy From The Mystic Dungeon

Special Array I

Find The Minimum Area To Cover All Ones Ii

Generate Binary Strings Without Adjacent Zeros

Minimum Number Of Flips To Make Binary Grid Palindromic Ii

Find The K Th Character In String Game Ii

Total Characters In String After Transformations Ii

Find Minimum Time To Reach Last Room I

Count Number Of Balanced Permutations

Maximum Frequency Of An Element After Performing Operations Ii

Adjacent Increasing Subarrays Detection Ii

Sum Of Good Subsequences

Zero Array Transformation Iii

Find The Maximum Number Of Fruits Collected

Maximum Subarray With Equal Products

Separate Squares Ii

Check If Digits Are Equal In String After Operations I

Unique 3 Digit Even Numbers

Design Spreadsheet

Maximum Unique Subarray Sum After Deletion

Find Closest Person

Path Existence Queries In A Graph Ii

Find Most Frequent Vowel And Consonant

Best Time To Buy And Sell Stock V

Count Partitions With Max Min Difference At Most K

Find Maximum Area Of A Triangle

Count Prime Gap Balanced Subarrays

Count Islands With Total Value Divisible By K

Partition Array For Maximum Xor And And

Maximum Total From Optimal Activation Order

Partition Array Into K Distinct Groups

Sum Of Beautiful Subsequences

Count Bowl Subarrays

Subsequence Sum After Capping Elements

Number Of Stable Subsequences

Sum Of Perfect Square Ancestors

Lexicographically Smallest Permutation Greater Than Target

Back to GoogleLeetCode Index

Microsoft — LeetCode Plan

This page groups Microsoft-focused practice plans.

Microsoft — 30 Days

Two Sum

Subarray Sum Equals K

Count The Number Of Infection Sequences

Add Two Numbers

Smallest String With Swaps

Design Authentication Manager

Reverse Integer

Palindrome Number

Longest Common Prefix

Valid Parentheses

Rotate Image

Number Of Islands

Minimum Number Of Steps To Make Two Strings Anagram

Longest Substring Without Repeating Characters

Integer To Roman

Remove Duplicates From Sorted Array

Jump Game Ii

Maximum Subarray

Sort Colors

Lru Cache

Calculate Money In Leetcode Bank

Minimum Operations To Reduce An Integer To 0

Smallest Number With All Set Bits

Longest Palindromic Substring

Regular Expression Matching

Container With Most Water

Reverse Nodes In K Group

Next Permutation

Valid Sudoku

Trapping Rain Water

Merge Intervals

Add Binary

Maximum Depth Of Binary Tree

Best Time To Buy And Sell Stock

Longest Consecutive Sequence

Find Minimum In Rotated Sorted Array

Min Stack

Course Schedule

Sliding Window Maximum

Meeting Rooms Ii

Coin Change

Insert Delete Getrandom O1

First Unique Character In A String

Battleships In A Board

Perfect Number

Number Of Provinces

Accounts Merge

Flood Fill

Daily Temperatures

Minimum Difficulty Of A Job Schedule

Check If The Sentence Is Pangram

Add Two Integers

Minimum Edge Reversals So Every Node Is Reachable

The Two Sneaky Numbers Of Digitville

Back to MicrosoftLeetCode Index

Microsoft — 90 Days

Two Sum

Add Two Numbers

Subarray Sum Equals K

Longest Substring Without Repeating Characters

Trapping Rain Water

Lru Cache

Best Time To Buy And Sell Stock

Longest Palindromic Substring

Group Anagrams

Merge Intervals

Median Of Two Sorted Arrays

Roman To Integer

Palindrome Number

Valid Parentheses

Remove Duplicates From Sorted Array

Maximum Subarray

Majority Element

Container With Most Water

Search In Rotated Sorted Array

Design Authentication Manager

Count The Number Of Infection Sequences

Reverse Integer

Longest Common Prefix

3sum

Reverse Nodes In K Group

Next Permutation

Daily Temperatures

Jump Game Ii

Rotate Image

Rising Temperature

Number Of Islands

Minimum Operations To Reduce An Integer To 0

Merge Two Sorted Lists

Merge K Sorted Lists

Restore Ip Addresses

Valid Anagram

Minimum Operations To Make Array Equal To Target

Remove Nth Node From End Of List

Valid Sudoku

First Missing Positive

Permutations

Spiral Matrix

Sort Colors

Merge Sorted Array

Gas Station

Linked List Cycle

Two Sum Ii Input Array Is Sorted

Lowest Common Ancestor Of A Binary Tree

Move Zeroes

Coin Change

First Unique Character In A String

Battleships In A Board

Vowel Spellchecker

Smallest String With Swaps

Calculate Money In Leetcode Bank

Regular Expression Matching

Integer To Roman

Generate Parentheses

Find The Index Of The First Occurrence In A String

Multiply Strings

N Queens

Jump Game

Climbing Stairs

Word Search

Largest Rectangle In Histogram

Same Tree

Maximum Depth Of Binary Tree

Populating Next Right Pointers In Each Node

Valid Palindrome

Find Minimum In Rotated Sorted Array

Find Peak Element

Course Schedule

Implement Trie Prefix Tree

Course Schedule Ii

Contains Duplicate

Sliding Window Maximum

Meeting Rooms Ii

Find The Duplicate Number

Top K Frequent Elements

Ransom Note

Split Array Largest Sum

Longest Repeating Character Replacement

Arranging Coins

Palindromic Substrings

Design Hashmap

Convert Integer To The Sum Of Two No Zero Integers

Minimum Number Of Steps To Make Two Strings Anagram

Running Sum Of 1d Array

Average Time Of Process Per Machine

Minimum Initial Energy To Finish Tasks

Add Two Integers

Zigzag Conversion

String To Integer Atoi

Remove Element

Divide Two Integers

Permutations Ii

Add Binary

Sqrtx

Simplify Path

Subsets

Reverse Linked List Ii

Binary Tree Zigzag Level Order Traversal

Pascals Triangle

Best Time To Buy And Sell Stock Ii

Longest Consecutive Sequence

Palindrome Partitioning

Candy

Word Break

Evaluate Reverse Polish Notation

Maximum Product Subarray

Excel Sheet Column Number

Largest Number

Rotate Array

Reverse Linked List

Word Search Ii

Find Median From Data Stream

Longest Increasing Subsequence

Design Hit Counter

Insert Delete Getrandom O1

Decode String

Longest Substring With At Least K Repeating Characters

Find All Anagrams In A String

Find All Duplicates In An Array

Single Element In A Sorted Array

Number Of Provinces

Maximum Average Subarray I

Find K Closest Elements

Accounts Merge

Special Binary String

Shifting Letters

Koko Eating Bananas

Subarrays With K Different Integers

Rotting Oranges

Max Consecutive Ones Iii

Average Selling Price

Maximal Network Rank

Recyclable And Low Fat Products

Check If The Sentence Is Pangram

Number Of Visible People In A Queue

Maximum Number Of Non Overlapping Palindrome Substrings

Minimum Edge Reversals So Every Node Is Reachable

Smallest Number With All Set Bits

4sum

Find First And Last Position Of Element In Sorted Array

Search Insert Position

Sudoku Solver

Combination Sum

Wildcard Matching

N Queens Ii

Length Of Last Word

Text Justification

Edit Distance

Maximal Rectangle

Binary Tree Inorder Traversal

Interleaving String

Recover Binary Search Tree

Binary Tree Level Order Traversal

Path Sum Ii

Best Time To Buy And Sell Stock Iii

Word Ladder

Single Number

Binary Tree Preorder Traversal

Sort List

Reverse Words In A String

Min Stack

Excel Sheet Column Title

Happy Number

Kth Largest Element In An Array

Number Of Digit One

Delete Node In A Linked List

Product Of Array Except Self

Add Digits

Missing Number

H Index

Game Of Life

Serialize And Deserialize Binary Tree

Odd Even Linked List

Intersection Of Two Arrays

Intersection Of Two Arrays Ii

Find K Pairs With Smallest Sums

Evaluate Division

Remove K Digits

Trapping Rain Water Ii

Fizz Buzz

Partition Equal Subset Sum

Flatten A Multilevel Doubly Linked List

Assign Cookies

Max Consecutive Ones

Next Greater Element I

Next Greater Element Ii

Perfect Number

Game Play Analysis Iv

Managers With At Least 5 Direct Reports

Design Circular Queue

Set Mismatch

Maximum Width Of Binary Tree

24 Game

Insert Into A Binary Search Tree

Flood Fill

Cherry Pickup

Is Graph Bipartite

Cheapest Flights Within K Stops

Minimum Number Of Refueling Stops

Middle Of The Linked List

Online Stock Span

Fruit Into Baskets

Minimize Malware Spread

Broken Calculator

Minimum Score Triangulation Of Polygon

Product Sales Analysis Iii

Shortest Path In Binary Matrix

Longest Common Subsequence

Article Views I

Monthly Transactions I

Minimum Knight Moves

Minimum Absolute Difference

Count Servers That Communicate

Minimum Difficulty Of A Job Schedule

Minimum Value To Get Positive Step By Step Sum

Rearrange Words In A Sentence

Final Prices With A Special Discount In A Shop

Longest Subarray Of 1s After Deleting One Element

Number Of Good Pairs

Find The Winner Of An Array Game

Get The Maximum Score

Customer Who Visited But Did Not Make Any Transactions

Primary Department For Each Employee

Count Good Numbers

Maximum Number Of Words You Can Type

Partition Array According To Given Pivot

Successful Pairs Of Spells And Potions

Number Of People Aware Of A Secret

Count Palindromic Subsequences

The Two Sneaky Numbers Of Digitville

Design Task Manager

Implement Router

Twisted Mirror Path Count

Back to MicrosoftLeetCode Index

Microsoft — 180 Days

Two Sum

Add Two Numbers

Longest Substring Without Repeating Characters

Median Of Two Sorted Arrays

Subarray Sum Equals K

Merge Intervals

Longest Palindromic Substring

Trapping Rain Water

Best Time To Buy And Sell Stock

3sum

Valid Parentheses

Group Anagrams

Lru Cache

Roman To Integer

Palindrome Number

Remove Duplicates From Sorted Array

Majority Element

Search In Rotated Sorted Array

Rotate Image

Longest Common Prefix

Maximum Subarray

Next Permutation

Spiral Matrix

Minimum Edge Reversals So Every Node Is Reachable

Container With Most Water

Reverse Nodes In K Group

Move Zeroes

Merge Sorted Array

Generate Parentheses

Largest Rectangle In Histogram

Reverse Integer

Jump Game Ii

Koko Eating Bananas

Merge Two Sorted Lists

Permutations

Pascals Triangle

Longest Consecutive Sequence

Gas Station

Number Of Islands

Happy Number

Contains Duplicate

Valid Anagram

Coin Change

Minimum Operations To Reduce An Integer To 0

Merge K Sorted Lists

Find The Index Of The First Occurrence In A String

Search Insert Position

Find Peak Element

Rising Temperature

Course Schedule Ii

Design Authentication Manager

Find First And Last Position Of Element In Sorted Array

Valid Sudoku

Sort Colors

Arranging Coins

Single Element In A Sorted Array

Daily Temperatures

Max Consecutive Ones Iii

Count The Number Of Infection Sequences

String To Integer Atoi

Regular Expression Matching

Sqrtx

Maximum Depth Of Binary Tree

House Robber

Reverse Linked List

Lowest Common Ancestor Of A Binary Tree

Sliding Window Maximum

Split Array Largest Sum

Longest Repeating Character Replacement

Number Of Provinces

Count Palindromic Subsequences

Valid Word

Integer To Roman

Remove Nth Node From End Of List

Combination Sum

First Missing Positive

N Queens

Jump Game

Climbing Stairs

Restore Ip Addresses

Binary Tree Level Order Traversal

Best Time To Buy And Sell Stock Ii

Valid Palindrome

Single Number

Linked List Cycle

Find Minimum In Rotated Sorted Array

Min Stack

Rotate Array

Minimum Size Subarray Sum

Product Of Array Except Self

Find Median From Data Stream

Serialize And Deserialize Binary Tree

Top K Frequent Elements

Ransom Note

Rotting Oranges

Minimum Difficulty Of A Job Schedule

Add Two Integers

Subsets

Binary Tree Inorder Traversal

Same Tree

Binary Tree Zigzag Level Order Traversal

Word Ladder

Word Break

Reverse Words In A String

Largest Number

Employees Earning More Than Their Managers

Implement Trie Prefix Tree

Meeting Rooms Ii

Perfect Squares

Find The Duplicate Number

Longest Increasing Subsequence

Intersection Of Two Arrays

Decode String

Find All Anagrams In A String

String Compression

Next Greater Element I

Vowel Spellchecker

Smallest String With Swaps

Recyclable And Low Fat Products

Frequency Of The Most Frequent Element

Minimum Operations To Make Array Equal To Target

Letter Combinations Of A Phone Number

Remove Element

Divide Two Integers

Longest Valid Parentheses

Sudoku Solver

Multiply Strings

Add Binary

Simplify Path

Word Search

Subsets Ii

Reverse Linked List Ii

Populating Next Right Pointers In Each Node

Linked List Cycle Ii

Maximum Product Subarray

Two Sum Ii Input Array Is Sorted

Second Highest Salary

Course Schedule

Kth Smallest Element In A Bst

First Unique Character In A String

Partition Equal Subset Sum

Battleships In A Board

Find All Duplicates In An Array

Max Consecutive Ones

Fibonacci Number

Game Play Analysis Iv

Can Place Flowers

Task Scheduler

Design Hashmap

Peak Index In A Mountain Array

Online Stock Span

Longest Common Subsequence

Minimum Absolute Difference

Maximum Number Of Events That Can Be Attended

Minimum Value To Get Positive Step By Step Sum

Running Sum Of 1d Array

Average Time Of Process Per Machine

Calculate Money In Leetcode Bank

Merge Strings Alternately

Maximum Number Of Alloys

Maximum Difference Between Even And Odd Frequency I

Combination Sum Ii

Permutations Ii

Powx N

Minimum Path Sum

Edit Distance

Set Matrix Zeroes

Maximal Rectangle

Interleaving String

Recover Binary Search Tree

Palindrome Partitioning

Sort List

Evaluate Reverse Polish Notation

Excel Sheet Column Number

Combine Two Tables

Word Search Ii

House Robber Ii

Kth Largest Element In An Array

Implement Stack Using Queues

Majority Element Ii

Palindrome Linked List

Delete Node In A Linked List

Meeting Rooms

Power Of Three

Odd Even Linked List

Perfect Number

Permutation In String

Managers With At Least 5 Direct Reports

Palindromic Substrings

Find K Closest Elements

24 Game

Accounts Merge

Special Binary String

Backspace String Compare

Subarrays With K Different Integers

Height Checker

Monthly Transactions I

Convert Integer To The Sum Of Two No Zero Integers

Minimum Number Of Steps To Make Two Strings Anagram

Find The Winner Of An Array Game

Customer Who Visited But Did Not Make Any Transactions

Minimum Initial Energy To Finish Tasks

Check If Array Is Sorted And Rotated

Primary Department For Each Employee

Count Good Numbers

Rearranging Fruits

Find The Original Typed String Ii

Zigzag Conversion

4sum

Swap Nodes In Pairs

Wildcard Matching

Length Of Last Word

Permutation Sequence

Rotate List

Unique Paths

Plus One

Text Justification

Minimum Window Substring

Remove Duplicates From Sorted Array Ii

Validate Binary Search Tree

Convert Sorted Array To Binary Search Tree

Balanced Binary Tree

Triangle

Best Time To Buy And Sell Stock Iii

Word Ladder Ii

Candy

Single Number Ii

Copy List With Random Pointer

Intersection Of Two Linked Lists

Delete Duplicate Emails

Binary Tree Right Side View

Contains Duplicate Ii

Contains Duplicate Iii

Implement Queue Using Stacks

Add Digits

Missing Number

H Index

Game Of Life

Remove Invalid Parentheses

Longest Substring With At Most K Distinct Characters

Intersection Of Two Arrays Ii

Design Hit Counter

Insert Delete Getrandom O1

Is Subsequence

Longest Substring With At Least K Repeating Characters

Remove K Digits

Fizz Buzz

Add Strings

K Th Smallest In Lexicographical Order

Delete Node In A Bst

Diagonal Traverse

Next Greater Element Ii

Next Greater Element Iii

Friend Requests Ii Who Has The Most Friends

Valid Triangle Number

Exclusive Time Of Functions

Maximum Average Subarray I

Maximum Width Of Binary Tree

Valid Palindrome Ii

Kth Largest Element In A Stream

Binary Search

Flood Fill

Asteroid Collision

Is Graph Bipartite

Split Array With Same Average

Rectangle Overlap

New 21 Game

Shifting Letters

All Nodes Distance K In Binary Tree

Middle Of The Linked List

Bitwise Ors Of Subarrays

Fruit Into Baskets

Snakes And Ladders

Subarray Sums Divisible By K

Vertical Order Traversal Of A Binary Tree

Number Of Enclaves

Greatest Common Divisor Of Strings

Shortest Path In Binary Matrix

Article Views I

Minimum Knight Moves

Maximum Profit In Job Scheduling

Average Selling Price

Search Suggestions System

Find N Unique Integers Sum Up To Zero

Number Of Substrings Containing All Three Characters

Find Lucky Integer In An Array

Maximum Points You Can Obtain From Cards

Final Prices With A Special Discount In A Shop

Longest Subarray Of 1s After Deleting One Element

Minimum Number Of Increments On Subarrays To Form A Target Array

Maximal Network Rank

Swapping Nodes In A Linked List

Sum Of Beauty Of All Substrings

Check If The Sentence Is Pangram

Maximum Number Of Words You Can Type

Number Of Visible People In A Queue

Kth Smallest Product Of Two Sorted Arrays

Longest Palindrome By Concatenating Two Letter Words

Maximum Number Of Non Overlapping Palindrome Substrings

To Be Or Not To Be

Count Elements With Maximum Frequency

Alice And Bob Playing Flower Game

Find The K Th Character In String Game I

Smallest Number With All Set Bits

Maximum Manhattan Distance After K Changes

Maximum Difference Between Even And Odd Frequency Ii

Maximum Unique Subarray Sum After Deletion

N Queens Ii

Insert Interval

Spiral Matrix Ii

Search A 2d Matrix

Combinations

Partition List

Decode Ways

Construct Binary Tree From Preorder And Inorder Traversal

Path Sum

Path Sum Ii

Populating Next Right Pointers In Each Node Ii

Sum Root To Leaf Numbers

Surrounded Regions

Palindrome Partitioning Ii

Clone Graph

Word Break Ii

Reorder List

Binary Tree Preorder Traversal

Excel Sheet Column Title

Factorial Trailing Zeroes

Consecutive Numbers

Reverse Bits

Design Add And Search Words Data Structure

The Skyline Problem

Maximal Square

Number Of Digit One

Lowest Common Ancestor Of A Binary Search Tree

Search A 2d Matrix Ii

Encode And Decode Strings

Integer To English Words

First Bad Version

Range Sum Query Immutable

Burst Balloons

Binary Tree Vertical Order Traversal

Wiggle Sort Ii

Reconstruct Itinerary

House Robber Iii

Counting Bits

Power Of Four

Reverse String

Design Tic Tac Toe

Logger Rate Limiter

Valid Perfect Square

Find K Pairs With Smallest Sums

Evaluate Division

Trapping Rain Water Ii

Longest Palindrome

Flatten A Multilevel Doubly Linked List

Minimum Genetic Mutation

Add Two Numbers Ii

Find All Numbers Disappeared In An Array

Serialize And Deserialize Bst

Assign Cookies

Lfu Cache

Island Perimeter

Optimal Account Balancing

Robot Room Cleaner

Reverse Pairs

Ipo

Longest Palindromic Subsequence

Continuous Subarray Sum

Convert Bst To Greater Tree

01 Matrix

Diameter Of Binary Tree

Boundary Of Binary Tree

Employee Bonus

Investments In 2016

Customer Placing The Largest Number Of Orders

Design In Memory File System

Big Countries

Classes With At Least 5 Students

Merge Two Binary Trees

Design Circular Queue

Set Mismatch

Valid Parenthesis String

Top K Frequent Words

Max Area Of Island

Insert Into A Binary Search Tree

Design Linked List

Best Time To Buy And Sell Stock With Transaction Fee

Split Linked List In Parts

Delete And Earn

Cherry Pickup

Network Delay Time

Open The Lock

Reorganize String

Jewels And Stones

Reaching Points

Cheapest Flights Within K Stops

Bus Routes

Making A Large Island

Consecutive Numbers Sum

Hand Of Straights

Reordered Power Of 2

Minimum Number Of Refueling Stops

Super Egg Drop

Sort An Array

Cat And Mouse

Sort Array By Parity Ii

Minimize Malware Spread

Binary Subarrays With Sum

Shortest Bridge

Check Completeness Of A Binary Tree

Interval List Intersections

Broken Calculator

Construct Binary Search Tree From Preorder Traversal

Minimum Score Triangulation Of Polygon

Remove All Adjacent Duplicates In String

Actors And Directors Who Cooperated At Least Three Times

Product Sales Analysis Iii

Car Pooling

Snapshot Array

As Far From Land As Possible

Immediate Food Delivery Ii

Unique Number Of Occurrences

The Dining Philosophers

Minimum Swaps To Make Strings Equal

Count Number Of Nice Subarrays

Count Servers That Communicate

Students And Examinations

Jump Game Iii

Maximum 69 Number

Movie Rating

Count Negative Numbers In A Sorted Matrix

Longest Happy Prefix

Count Good Nodes In Binary Tree

Rearrange Words In A Sentence

Reorder Routes To Make All Paths Lead To The City Zero

Number Of Good Pairs

Water Bottles

Count Odd Numbers In An Interval Range

Minimum Suffix Flips

Get The Maximum Score

Kth Missing Positive Number

Min Cost To Connect All Points

Ways To Make A Fair Array

Merge In Between Linked Lists

Richest Customer Wealth

Maximum Erasure Value

Maximum Average Pass Ratio

Maximum Population Year

Sorting The Sentence

Concatenation Of Array

Delete Duplicate Folders In System

Finding 3 Digit Even Numbers

Sum Of Subarray Ranges

Partition Array According To Given Pivot

Find Resultant Array After Removing Anagrams

Design A Text Editor

Successful Pairs Of Spells And Potions

Number Of People Aware Of A Secret

Number Of Zero Filled Subarrays

Meeting Rooms Iii

Longest Subarray With Maximum Bitwise And

Find The Original Array Of Prefix Xor

Count Subarrays With Fixed Bounds

Minimum Cost To Make Array Equal

Minimum Penalty For A Shop

Design Memory Allocator

Maximum Subsequence Score

Maximize Greatness Of An Array

Minimize The Maximum Difference Of Pairs

Check If Object Instance Of Class

Counter

Create Hello World Function

Maximum Or

Find The Maximum Achievable Number

Insert Greatest Common Divisors In Linked List

Harshad Number

Find The Minimum Area To Cover All Ones I

Find The Minimum Area To Cover All Ones Ii

Find The Maximum Length Of Valid Subsequence I

Find The Maximum Length Of Valid Subsequence Ii

Delete Nodes From Linked List Present In Array

The Two Sneaky Numbers Of Digitville

Make Array Elements Equal To Zero

Zero Array Transformation I

Zero Array Transformation Iii

Design Task Manager

Fruits Into Baskets Ii

Fruits Into Baskets Iii

Maximize Subarrays After Removing One Conflicting Pair

Implement Router

Transform Array To All Equal Elements

Twisted Mirror Path Count

Back to MicrosoftLeetCode Index

Facebook — LeetCode Plan

This page groups Facebook-focused practice plans.

Facebook — 30 Days

Valid Word Abbreviation

Valid Palindrome Ii

Minimum Remove To Make Valid Parentheses

Binary Tree Right Side View

Simplify Path

Kth Largest Element In An Array

Diameter Of Binary Tree

Two Sum

Merge Intervals

Subarray Sum Equals K

Making A Large Island

Sum Root To Leaf Numbers

Binary Tree Vertical Order Traversal

Lru Cache

Random Pick With Weight

Powx N

Basic Calculator Ii

Top K Frequent Elements

Maximum Swap

Custom Sort String

Add Two Numbers

Merge Sorted Array

Valid Palindrome

Lowest Common Ancestor Of A Binary Tree

Max Consecutive Ones Iii

Lowest Common Ancestor Of A Binary Tree Iii

Buildings With An Ocean View

Next Permutation

Longest Valid Parentheses

Nested List Weight Sum

Exclusive Time Of Functions

K Closest Points To Origin

Simple Bank System

Valid Parentheses

Remove Duplicates From Sorted Array

Strobogrammatic Number

Random Pick Index

Range Sum Of Bst

Best Time To Buy And Sell Stock

Copy List With Random Pointer

Find Peak Element

Boundary Of Binary Tree

Interval List Intersections

Remove Nth Node From End Of List

Rotate Image

Add Strings

Palindromic Substrings

Max Area Of Island

Friends Of Appropriate Ages

All Nodes Distance K In Binary Tree

Remove All Adjacent Duplicates In String

Shortest Path In Binary Matrix

Kids With The Greatest Number Of Candies

Dot Product Of Two Sparse Vectors

Count Unguarded Cells In The Grid

Count Nodes Equal To Average Of Subtree

Longest Palindromic Substring

String To Integer Atoi

3sum

3sum Closest

Generate Parentheses

Merge K Sorted Lists

Find First And Last Position Of Element In Sorted Array

Minimum Window Substring

Subsets

Word Ladder

Insert Delete Getrandom O1

Convert Binary Search Tree To Sorted Doubly Linked List

Kth Missing Positive Number

Regular Expression Matching

Container With Most Water

Group Anagrams

Climbing Stairs

Reverse Linked List Ii

Binary Tree Level Order Traversal

Gas Station

Insertion Sort List

Intersection Of Two Linked Lists

Missing Ranges

Majority Element

Number Of Islands

Course Schedule

Contains Duplicate Ii

Sliding Window Maximum

Alien Dictionary

Closest Binary Search Tree Value

Find Median From Data Stream

Range Sum Query Immutable

Kth Smallest Element In A Sorted Matrix

Decode String

Pacific Atlantic Water Flow

Longest Repeating Character Replacement

Validate Ip Address

Robot Room Cleaner

Diagonal Traverse

Continuous Subarray Sum

Game Play Analysis Iv

Can Place Flowers

Binary Search

Insert Into A Sorted Circular Linked List

Accounts Merge

Find Pivot Index

Goat Latin

Koko Eating Bananas

Minimum Add To Make Parentheses Valid

Capacity To Ship Packages Within D Days

Car Pooling

Longest Common Subsequence

Unique Number Of Occurrences

Students And Examinations

Finding Pairs With A Certain Sum

Product Of Two Run Length Encoded Arrays

Maximum Frequency Of An Element After Performing Operations I

Make Array Elements Equal To Zero

Check If Digits Are Equal In String After Operations I

Best Time To Buy And Sell Stock Using Strategy

Back to FacebookLeetCode Index

Facebook — 90 Days

Minimum Remove To Make Valid Parentheses

Valid Word Abbreviation

Valid Palindrome Ii

Kth Largest Element In An Array

Binary Tree Right Side View

Diameter Of Binary Tree

Subarray Sum Equals K

Lowest Common Ancestor Of A Binary Tree

Basic Calculator Ii

Random Pick With Weight

Binary Tree Vertical Order Traversal

Two Sum

Nested List Weight Sum

Merge Intervals

Simplify Path

Valid Palindrome

Sum Root To Leaf Numbers

Top K Frequent Elements

Lowest Common Ancestor Of A Binary Tree Iii

Buildings With An Ocean View

Copy List With Random Pointer

Lru Cache

Making A Large Island

Shortest Path In Binary Matrix

Best Time To Buy And Sell Stock

Powx N

K Closest Points To Origin

Valid Parentheses

Next Permutation

Merge Sorted Array

Find Peak Element

Find First And Last Position Of Element In Sorted Array

Add Two Numbers

Custom Sort String

Minimum Window Substring

Max Consecutive Ones Iii

Longest Valid Parentheses

Exclusive Time Of Functions

All Nodes Distance K In Binary Tree

Minimum Add To Make Parentheses Valid

Dot Product Of Two Sparse Vectors

Simple Bank System

Count Nodes Equal To Average Of Subtree

Course Schedule

Add Strings

Palindromic Substrings

Clone Graph

Longest Substring Without Repeating Characters

Remove Nth Node From End Of List

Robot Room Cleaner

Range Sum Of Bst

Merge K Sorted Lists

Diagonal Traverse

Vertical Order Traversal Of A Binary Tree

Kth Missing Positive Number

Container With Most Water

Moving Average From Data Stream

Insert Into A Sorted Circular Linked List

Friends Of Appropriate Ages

3sum

Valid Number

Strobogrammatic Number

Closest Binary Search Tree Value

Random Pick Index

Maximum Swap

Longest Palindromic Substring

Remove Duplicates From Sorted Array

Set Matrix Zeroes

Median Of Two Sorted Arrays

String To Integer Atoi

Palindrome Number

Trapping Rain Water

Maximum Subarray

Word Ladder

Contains Duplicate Ii

Alien Dictionary

Sliding Window Median

Boundary Of Binary Tree

Max Area Of Island

Goat Latin

Interval List Intersections

Regular Expression Matching

Longest Common Prefix

Generate Parentheses

Sort Colors

Subsets

Sliding Window Maximum

Design Tic Tac Toe

Swim In Rising Water

Koko Eating Bananas

3sum Closest

Rotate Image

Best Time To Buy And Sell Stock Ii

Majority Element

Group Shifted Strings

Insert Delete Getrandom O1

Convert Binary Search Tree To Sorted Doubly Linked List

Accounts Merge

Missing Element In Sorted Array

Remove All Adjacent Duplicates In String Ii

Kids With The Greatest Number Of Candies

Remove Element

Group Anagrams

Spiral Matrix

Unique Paths

Populating Next Right Pointers In Each Node

Gas Station

Missing Ranges

Range Sum Query Immutable

Kth Smallest Element In A Sorted Matrix

Longest Repeating Character Replacement

Continuous Subarray Sum

Find K Closest Elements

Find Pivot Index

Capacity To Ship Packages Within D Days

Remove All Adjacent Duplicates In String

Best Time To Buy And Sell Stock Using Strategy

Roman To Integer

Search Insert Position

Jump Game

Plus One

Pascals Triangle

Binary Search Tree Iterator

Rising Temperature

Number Of Islands

Power Of Two

Meeting Rooms Ii

Walls And Gates

Find Median From Data Stream

Sparse Matrix Multiplication

Coin Change

Odd Even Linked List

Decode String

Battleships In A Board

Target Sum

Single Element In A Sorted Array

Managers With At Least 5 Direct Reports

Check Completeness Of A Binary Tree

Unique Number Of Occurrences

Count Unguarded Cells In The Grid

Fruits Into Baskets Ii

Reverse Integer

4sum

Merge Two Sorted Lists

Divide Two Integers

Search In Rotated Sorted Array

Permutations

N Queens

Add Binary

Sqrtx

Climbing Stairs

Largest Rectangle In Histogram

Validate Binary Search Tree

Binary Tree Maximum Path Sum

Word Ladder Ii

Fraction To Recurring Decimal

Rotate Array

Count Primes

Reverse Linked List

Course Schedule Ii

Contains Duplicate

The Skyline Problem

Basic Calculator

Valid Anagram

First Bad Version

Move Zeroes

Longest Increasing Path In A Matrix

Intersection Of Two Arrays

Pacific Atlantic Water Flow

String Compression

Sort Characters By Frequency

Max Consecutive Ones

Construct Binary Tree From String

Can Place Flowers

Merge Two Binary Trees

24 Game

Binary Search

Open The Lock

Peak Index In A Mountain Array

Sort Array By Parity

Minimum Cost For Tickets

Lowest Common Ancestor Of Deepest Leaves

Valid Palindrome Iii

Students And Examinations

Shortest Path In A Grid With Obstacles Elimination

Minimum Time To Collect All Apples In A Tree

Count Good Numbers

Add Two Integers

Minimum Operations To Make The Integer Zero

Count Elements With Maximum Frequency

Valid Sudoku

Sudoku Solver

Length Of Last Word

Rotate List

Word Search

Subsets Ii

Reverse Linked List Ii

Same Tree

Binary Tree Level Order Traversal

Binary Tree Level Order Traversal Ii

Balanced Binary Tree

Flatten Binary Tree To Linked List

Best Time To Buy And Sell Stock Iii

Surrounded Regions

Single Number

Insertion Sort List

Sort List

Intersection Of Two Linked Lists

Two Sum Ii Input Array Is Sorted

Combine Two Tables

Rank Scores

Largest Number

Reverse Bits

Tenth Line

Delete Duplicate Emails

House Robber

Happy Number

Isomorphic Strings

House Robber Ii

Palindrome Linked List

Lowest Common Ancestor Of A Binary Search Tree

Delete Node In A Linked List

Search A 2d Matrix Ii

Missing Number

Expression Add Operators

Find The Duplicate Number

Serialize And Deserialize Binary Tree

Remove Invalid Parentheses

Shortest Distance From All Buildings

Bulb Switcher

Flatten Nested List Iterator

Integer Break

Reverse String

Reverse Vowels Of A String

Remove K Digits

Partition Equal Subset Sum

Validate Ip Address

Next Greater Element I

Contiguous Array

01 Matrix

Game Play Analysis Iv

Next Greater Element Iii

Human Traffic Of Stadium

Friend Requests Ii Who Has The Most Friends

Valid Parenthesis String

Top K Frequent Words

Design Hashmap

Min Cost Climbing Stairs

Toeplitz Matrix

Rabbits In Forest

Letter Case Permutation

Rotate String

Transpose Matrix

Monotonic Array

Sum Of Subarray Minimums

Shortest Bridge

Largest Perimeter Triangle

Squares Of A Sorted Array

Rotting Oranges

Minimum Score Triangulation Of Polygon

Car Pooling

User Activity For The Past 30 Days I

Longest Common Subsequence

Article Views I

Find Words That Can Be Formed By Characters

Monthly Transactions I

Design Skiplist

Average Selling Price

Rank Transform Of An Array

Maximum Points You Can Obtain From Cards

Customer Who Visited But Did Not Make Any Transactions

Average Time Of Process Per Machine

Swapping Nodes In A Linked List

Sum Of Beauty Of All Substrings

Finding Pairs With A Certain Sum

Product Of Two Run Length Encoded Arrays

Minimize Maximum Pair Sum In Array

Remove All Occurrences Of A Substring

Next Greater Numerically Balanced Number

Successful Pairs Of Spells And Potions

Number Of Zero Filled Subarrays

Count The Number Of Infection Sequences

Find The Xor Of Numbers Which Appear Twice

Maximum Frequency Of An Element After Performing Operations I

Make Array Elements Equal To Zero

Check If Digits Are Equal In String After Operations I

Find The Minimum Amount Of Time To Brew Potions

Find Most Frequent Vowel And Consonant

Compute Decimal Representation

Back to FacebookLeetCode Index

Facebook — 180 Days

Minimum Remove To Make Valid Parentheses

Valid Word Abbreviation

Valid Palindrome Ii

Kth Largest Element In An Array

Binary Tree Right Side View

Binary Tree Vertical Order Traversal

Random Pick With Weight

Nested List Weight Sum

Basic Calculator Ii

Lowest Common Ancestor Of A Binary Tree

Diameter Of Binary Tree

Merge Intervals

Lowest Common Ancestor Of A Binary Tree Iii

Two Sum

Simplify Path

Subarray Sum Equals K

Find Peak Element

Powx N

Top K Frequent Elements

Best Time To Buy And Sell Stock

Shortest Path In Binary Matrix

Buildings With An Ocean View

Sum Root To Leaf Numbers

Merge Sorted Array

Valid Palindrome

Next Permutation

Making A Large Island

Lru Cache

Copy List With Random Pointer

K Closest Points To Origin

Minimum Window Substring

Dot Product Of Two Sparse Vectors

Range Sum Of Bst

Valid Parentheses

Max Consecutive Ones Iii

Find First And Last Position Of Element In Sorted Array

Custom Sort String

Minimum Add To Make Parentheses Valid

Maximum Swap

Clone Graph

Exclusive Time Of Functions

Add Two Numbers

Longest Common Prefix

Course Schedule

Vertical Order Traversal Of A Binary Tree

Merge K Sorted Lists

Moving Average From Data Stream

Diagonal Traverse

Kth Missing Positive Number

Longest Substring Without Repeating Characters

Palindromic Substrings

Interval List Intersections

Longest Palindromic Substring

Add Strings

Sliding Window Median

All Nodes Distance K In Binary Tree

Count Nodes Equal To Average Of Subtree

Remove Nth Node From End Of List

Valid Number

3sum

Remove Duplicates From Sorted Array

Robot Room Cleaner

Insert Into A Sorted Circular Linked List

Container With Most Water

Closest Binary Search Tree Value

Binary Search Tree Iterator

Strobogrammatic Number

Goat Latin

Longest Valid Parentheses

Maximum Subarray

Subsets

Group Shifted Strings

String To Integer Atoi

Missing Element In Sorted Array

Valid Palindrome Iii

Palindrome Number

Set Matrix Zeroes

Sort Colors

Missing Ranges

Kth Smallest Element In A Sorted Matrix

Random Pick Index

Koko Eating Bananas

Simple Bank System

Trapping Rain Water

Contains Duplicate Ii

Accounts Merge

Median Of Two Sorted Arrays

Roman To Integer

Search In Rotated Sorted Array

Number Of Islands

Group Anagrams

Word Ladder

Sliding Window Maximum

Convert Binary Search Tree To Sorted Doubly Linked List

Boundary Of Binary Tree

Friends Of Appropriate Ages

Check Completeness Of A Binary Tree

Squares Of A Sorted Array

Remove All Adjacent Duplicates In String Ii

Find Median From Data Stream

Peak Index In A Mountain Array

Capacity To Ship Packages Within D Days

4sum

Merge Two Sorted Lists

Generate Parentheses

Best Time To Buy And Sell Stock Iii

Majority Element

Move Zeroes

Range Sum Query Immutable

Design Tic Tac Toe

Continuous Subarray Sum

Swim In Rising Water

Rotate Image

Unique Paths

Populating Next Right Pointers In Each Node

Insert Delete Getrandom O1

Decode String

Single Element In A Sorted Array

Reverse Integer

Climbing Stairs

Binary Tree Level Order Traversal

Pascals Triangle

Best Time To Buy And Sell Stock Ii

Binary Tree Maximum Path Sum

Remove Invalid Parentheses

Odd Even Linked List

Longest Repeating Character Replacement

Max Area Of Island

Shortest Bridge

Minimum Deletions For At Most K Distinct Characters

Regular Expression Matching

3sum Closest

Remove Element

Search Insert Position

Gas Station

Course Schedule Ii

Palindrome Linked List

Meeting Rooms Ii

Alien Dictionary

Expression Add Operators

Coin Change

Next Greater Element Iii

Find Pivot Index

Remove All Adjacent Duplicates In String

Article Views I

Spiral Matrix

Jump Game

Text Justification

Palindrome Partitioning

Single Number

Word Break

Rotate Array

Shortest Distance From All Buildings

Longest Increasing Path In A Matrix

Battleships In A Board

Construct Binary Tree From String

Managers With At Least 5 Direct Reports

Can Place Flowers

Car Pooling

Diagonal Traverse Ii

Kids With The Greatest Number Of Candies

Add Two Integers

Find The Index Of The First Occurrence In A String

Plus One

Largest Rectangle In Histogram

Maximal Rectangle

Subsets Ii

Longest Consecutive Sequence

Contains Duplicate

Power Of Two

Valid Anagram

Walls And Gates

Longest Increasing Subsequence

Intersection Of Two Arrays

Find K Closest Elements

Rotting Oranges

Product Of Two Run Length Encoded Arrays

Maximum Difference By Remapping A Digit

Zigzag Conversion

Letter Combinations Of A Phone Number

Reverse Nodes In K Group

Multiply Strings

Permutations

Combinations

Decode Ways

Binary Tree Inorder Traversal

Validate Binary Search Tree

Same Tree

Binary Tree Zigzag Level Order Traversal

Reverse Bits

Reverse Linked List

Basic Calculator

Lowest Common Ancestor Of A Binary Search Tree

Delete Node In A Linked List

Strobogrammatic Number Ii

Serialize And Deserialize Binary Tree

Sparse Matrix Multiplication

String Compression

The Maze

Next Greater Element I

Next Greater Element Ii

Binary Search

Longest Common Subsequence

Fruits Into Baskets Ii

Divide Two Integers

Combination Sum Ii

First Missing Positive

N Queens

Add Binary

Sqrtx

Search A 2d Matrix

Unique Binary Search Trees

Minimum Depth Of Binary Tree

Triangle

Reverse Words In A String

Min Stack

Two Sum Ii Input Array Is Sorted

Largest Number

Rising Temperature

Minimum Size Subarray Sum

House Robber Ii

Search A 2d Matrix Ii

First Bad Version

Reverse String

Pacific Atlantic Water Flow

Sort Characters By Frequency

Merge Two Binary Trees

Design Circular Queue

Repeated String Match

Asteroid Collision

Min Cost Climbing Stairs

Rotate String

Middle Of The Linked List

Monotonic Array

Sum Of Subarray Minimums

Monthly Transactions I

Average Selling Price

Maximum Number Of Events That Can Be Attended

Minimum Time To Collect All Apples In A Tree

Merge Strings Alternately

Frequency Of The Most Frequent Element

Largest Color Value In A Directed Graph

Cutting Ribbons

Minimize The Maximum Difference Of Pairs

Distribute Candies Among Children Ii

Best Time To Buy And Sell Stock Using Strategy

Integer To Roman

Valid Sudoku

Sudoku Solver

Wildcard Matching

Search In Rotated Sorted Array Ii

Reverse Linked List Ii

Interleaving String

Word Ladder Ii

Linked List Cycle

Reorder List

Maximum Product Subarray

Intersection Of Two Linked Lists

Fraction To Recurring Decimal

Second Highest Salary

Rank Scores

Happy Number

Count Primes

Isomorphic Strings

Implement Stack Using Queues

Kth Smallest Element In A Bst

Find The Duplicate Number

Increasing Triplet Subsequence

Reverse Vowels Of A String

Is Subsequence

Remove K Digits

Non Overlapping Intervals

Max Consecutive Ones

Target Sum

Contiguous Array

Minesweeper

Big Countries

Task Scheduler

Maximum Width Of Binary Tree

Design Hashmap

Toeplitz Matrix

Letter Case Permutation

Online Stock Span

Fruit Into Baskets

Sort Array By Parity

Number Of Recent Calls

Minimum Cost For Tickets

Customers Who Bought All Products

Maximum Level Sum Of A Binary Tree

Design Skiplist

Unique Number Of Occurrences

Students And Examinations

Shortest Path In A Grid With Obstacles Elimination

Find Lucky Integer In An Array

Lowest Common Ancestor Of A Binary Tree Ii

Check If Two String Arrays Are Equivalent

Max Number Of K Sum Pairs

Recyclable And Low Fat Products

Sum Of Beauty Of All Substrings

Finding 3 Digit Even Numbers

Find Subsequence Of Length K With The Largest Sum

Rearrange Array Elements By Sign

Count Unguarded Cells In The Grid

Count Elements With Maximum Frequency

Find The K Th Character In String Game I

Find Most Frequent Vowel And Consonant

Jump Game Ii

Rotate List

Minimum Path Sum

Word Search

Unique Binary Search Trees Ii

Construct Binary Tree From Preorder And Inorder Traversal

Binary Tree Level Order Traversal Ii

Balanced Binary Tree

Path Sum Ii

Flatten Binary Tree To Linked List

Populating Next Right Pointers In Each Node Ii

Candy

Sort List

Max Points On A Line

Find Minimum In Rotated Sorted Array

Combine Two Tables

Employees Earning More Than Their Managers

Customers Who Never Order

Repeated Dna Sequences

Tenth Line

Implement Trie Prefix Tree

The Skyline Problem

Product Of Array Except Self

Missing Number

Bulb Switcher

Counting Bits

Flatten Nested List Iterator

Partition Equal Subset Sum

Reverse Pairs

Coin Change Ii

Game Play Analysis Iv

Friend Requests Ii Who Has The Most Friends

Exchange Seats

Sum Of Square Numbers

Valid Parenthesis String

24 Game

Redundant Connection

Maximum Sum Of 3 Non Overlapping Subarrays

Subarray Product Less Than K

Open The Lock

Number Of Matching Subsequences

New 21 Game

Smallest Subtree With All The Deepest Nodes

Snakes And Ladders

Minimum Falling Path Sum

Binary Tree Cameras

Longest String Chain

Lowest Common Ancestor Of Deepest Leaves

Count Number Of Nice Subarrays

Count Square Submatrices With All Ones

Find The Smallest Divisor Given A Threshold

Element Appearing More Than 25 In Sorted Array

Maximum Number Of Occurrences Of A Substring

Number Of Operations To Make Network Connected

Rank Transform Of An Array

Maximum Sum Bst In Binary Tree

Maximum Points You Can Obtain From Cards

Consecutive Characters

Running Sum Of 1d Array

Three Consecutive Odds

Richest Customer Wealth

Find Minimum Time To Finish All Jobs

Shortest Path In A Hidden Grid

Remove All Occurrences Of A Substring

Count Good Numbers

Check If A Parentheses String Can Be Valid

Find All K Distant Indices In An Array

Successful Pairs Of Spells And Potions

Collect Coins In A Tree

Minimum Operations To Make The Integer Zero

Find The Peaks

Zero Array Transformation Iii

Find The Minimum Amount Of Time To Brew Potions

Combination Sum

Permutations Ii

Length Of Last Word

Unique Paths Ii

Remove Duplicates From Sorted Array Ii

Remove Duplicates From Sorted List

Restore Ip Addresses

Recover Binary Search Tree

Path Sum

Distinct Subsequences

Surrounded Regions

Palindrome Partitioning Ii

Linked List Cycle Ii

Insertion Sort List

Number Of 1 Bits

Delete Duplicate Emails

House Robber

Remove Linked List Elements

Word Search Ii

Invert Binary Tree

Implement Queue Using Stacks

Ugly Number Ii

Find The Celebrity

Game Of Life

Nim Game

Binary Tree Longest Consecutive Sequence

Remove Duplicate Letters

Power Of Three

Largest Bst Subtree

Integer Break

Intersection Of Two Arrays Ii

Valid Perfect Square

Find K Pairs With Smallest Sums

First Unique Character In A String

Evaluate Division

Trapping Rain Water Ii

Longest Palindrome

Split Array Largest Sum

Arithmetic Slices

Maximum Xor Of Two Numbers In An Array

Flatten A Multilevel Doubly Linked List

Path Sum Iii

Find All Anagrams In A String

Add Two Numbers Ii

132 Pattern

Island Perimeter

Validate Ip Address

Matchsticks To Square

Longest Uncommon Subsequence I

Complex Number Multiplication

Reverse String Ii

01 Matrix

Number Of Provinces

Investments In 2016

Longest Harmonious Subsequence

Human Traffic Of Stadium

Find Duplicate File In System

Triangle Judgement

Valid Triangle Number

Add Bold Tag In String

Swap Salary

Smallest Range Covering Elements From K Lists

Average Of Levels In Binary Tree

Maximum Average Subarray I

Non Decreasing Array

Top K Frequent Words

Cherry Pickup

Network Delay Time

Partition Labels

Jewels And Stones

Rabbits In Forest

Cheapest Flights Within K Stops

All Paths From Source To Target

Most Profit Assigning Work

Rectangle Overlap

Backspace String Compare

Hand Of Straights

Lemonade Change

Transpose Matrix

Binary Subarrays With Sum

Valid Mountain Array

Most Stones Removed With Same Row Or Column

Verifying An Alien Dictionary

Subarray Sums Divisible By K

Largest Perimeter Triangle

Unique Paths Iii

Cousins In Binary Tree

Construct Binary Search Tree From Preorder Traversal

Best Sightseeing Pair

Remove Outermost Parentheses

Sum Of Root To Leaf Binary Numbers

Minimum Score Triangulation Of Polygon

Distant Barcodes

Product Sales Analysis I

Product Sales Analysis Iii

Greatest Common Divisor Of Strings

Parsing A Boolean Expression

User Activity For The Past 30 Days I

Find Words That Can Be Formed By Characters

Immediate Food Delivery Ii

Reformat Department Table

Minimum Knight Moves

Last Person To Fit In The Bus

Queries Quality And Percentage

Find Winner On A Tic Tac Toe Game

Convert Binary Number In A Linked List To Integer

Find N Unique Integers Sum Up To Zero

Maximum 69 Number

Movie Rating

Count Negative Numbers In A Sorted Matrix

Product Of The Last K Numbers

Validate Binary Tree Nodes

Replace Employee Id With The Unique Identifier

Destination City

Course Schedule Iv

Shuffle The Array

Minimum Number Of Days To Make M Bouquets

Clone Binary Tree With Random Pointer

Avoid Flood In The City

Find Root Of N Ary Tree

Diameter Of N Ary Tree

Minimum Number Of Vertices To Reach All Nodes

Customer Who Visited But Did Not Make Any Transactions

Sort Array By Increasing Frequency

Average Time Of Process Per Machine

Maximum Score From Removing Substrings

Swapping Nodes In A Linked List

Find The Highest Altitude

Check If Array Is Sorted And Rotated

Primary Department For Each Employee

Maximum Average Pass Ratio

Check If The Sentence Is Pangram

Finding Pairs With A Certain Sum

Minimize Maximum Pair Sum In Array

The Earliest And Latest Rounds Where Players Compete

Find A Peak Element Ii

Maximum Alternating Subsequence Sum

Concatenation Of Array

Painting A Grid With Three Different Colors

Maximum Difference Between Increasing Elements

Next Greater Numerically Balanced Number

Sum Of K Mirror Numbers

Longest Palindrome By Concatenating Two Letter Words

Maximum Candies Allocated To K Children

Count Number Of Rectangles Containing Each Point

Minimum Score After Removals On A Tree

Decode The Message

Smallest Number In Infinite Set

Number Of Zero Filled Subarrays

Smallest Subarrays With Maximum Bitwise Or

Number Of Pairs Satisfying Inequality

Design Memory Allocator

Rearranging Fruits

Merge Two 2d Arrays By Summing Values

Find The Prefix Common Array Of Two Arrays

To Be Or Not To Be

Count Symmetric Integers

Divisible And Non Divisible Sums Difference

Count The Number Of Infection Sequences

Find Missing And Repeated Values

Maximum Area Of Longest Diagonal Rectangle

Find The Number Of Ways To Place People I

Find The Number Of Ways To Place People Ii

Find The Xor Of Numbers Which Appear Twice

Lexicographically Minimum String After Removing Stars

Find The Maximum Length Of Valid Subsequence I

Vowels Game In A String

Find The Original Typed String I

Maximum Frequency Of An Element After Performing Operations I

Make Array Elements Equal To Zero

Find The Lexicographically Largest String From The Box I

Maximum Difference Between Adjacent Elements In A Circular Array

Maximum Manhattan Distance After K Changes

Check If Digits Are Equal In String After Operations I

Maximum Unique Subarray Sum After Deletion

Find Closest Person

Grid Teleportation Traversal

Partition Array Into Two Equal Product Subsets

Count Number Of Trapezoids Ii

Compute Decimal Representation

Back to FacebookLeetCode Index

Netflix — LeetCode Plan

This page groups Netflix-focused practice plans.

Netflix — 30 Days

Problem List

Course Schedule Ii

Contains Duplicate Iii

Back to NetflixLeetCode Index

Netflix — 90 Days

Contains Duplicate Iii

Longest Substring Without Repeating Characters

Course Schedule Ii

Network Delay Time

Time Based Key Value Store

Cache With Time Limit

Back to NetflixLeetCode Index

Netflix — 180 Days

Contains Duplicate Iii

Time Based Key Value Store

Longest Substring Without Repeating Characters

Course Schedule Ii

Contains Duplicate Ii

Network Delay Time

Cache With Time Limit

Word Search

Contains Duplicate

Back to NetflixLeetCode Index

Apple (Alternate) — LeetCode Plan

Alternate Apple group. Keep this if you want a second Apple plan or split tracks.

Apple (Alternate)

— 30 Days

https://leetcode.com/problems/basic-calculator-ii https://leetcode.com/problems/course-schedule https://leetcode.com/problems/course-schedule-ii https://leetcode.com/problems/design-hit-counter https://leetcode.com/problems/find-median-from-data-stream https://leetcode.com/problems/lru-cache https://leetcode.com/problems/maximum-path-quality-of-a-graph https://leetcode.com/problems/maximum-subarray https://leetcode.com/problems/merge-intervals https://leetcode.com/problems/merge-k-sorted-lists https://leetcode.com/problems/product-of-array-except-self https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string https://leetcode.com/problems/reverse-linked-list https://leetcode.com/problems/rotate-array https://leetcode.com/problems/rotate-image https://leetcode.com/problems/serialize-and-deserialize-binary-tree https://leetcode.com/problems/spiral-matrix https://leetcode.com/problems/time-based-key-value-store https://leetcode.com/problems/top-k-frequent-elements https://leetcode.com/problems/two-sum

Back to Apple (alt) LeetCode Index

Apple (Alternate) — 90 Days

https://leetcode.com/problems/basic-calculator-ii https://leetcode.com/problems/best-time-to-buy-and-sell-stock https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee https://leetcode.com/problems/course-schedule https://leetcode.com/problems/course-schedule-ii https://leetcode.com/problems/decode-string https://leetcode.com/problems/design-add-and-search-words-data-structure https://leetcode.com/problems/design-hashmap https://leetcode.com/problems/design-hit-counter https://leetcode.com/problems/distribute-money-to-maximum-children https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array https://leetcode.com/problems/find-median-from-data-stream https://leetcode.com/problems/group-anagrams https://leetcode.com/problems/implement-queue-using-stacks https://leetcode.com/problems/implement-trie-prefix-tree https://leetcode.com/problems/intersection-of-two-arrays https://leetcode.com/problems/longest-substring-without-repeating-characters https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree https://leetcode.com/problems/lru-cache https://leetcode.com/problems/maximum-path-quality-of-a-graph https://leetcode.com/problems/maximum-subarray https://leetcode.com/problems/merge-intervals https://leetcode.com/problems/merge-k-sorted-lists https://leetcode.com/problems/middle-of-the-linked-list https://leetcode.com/problems/minimize-maximum-component-cost https://leetcode.com/problems/move-zeroes https://leetcode.com/problems/number-of-islands https://leetcode.com/problems/product-of-array-except-self https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string https://leetcode.com/problems/remove-duplicates-from-sorted-array https://leetcode.com/problems/reverse-linked-list https://leetcode.com/problems/rotate-array https://leetcode.com/problems/rotate-image https://leetcode.com/problems/serialize-and-deserialize-binary-tree https://leetcode.com/problems/short-encoding-of-words https://leetcode.com/problems/spiral-matrix https://leetcode.com/problems/time-based-key-value-store https://leetcode.com/problems/top-k-frequent-elements https://leetcode.com/problems/two-sum https://leetcode.com/problems/valid-palindrome https://leetcode.com/problems/valid-parentheses https://leetcode.com/problems/valid-sudoku

Back to Apple (alt)LeetCode Index

Apple (Alternate) — 180 Days

url https://leetcode.com/problems/alien-dictionary https://leetcode.com/problems/basic-calculator-ii https://leetcode.com/problems/best-time-to-buy-and-sell-stock https://leetcode.com/problems/best-time-to-buy-and-sell-stock-ii https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iii https://leetcode.com/problems/best-time-to-buy-and-sell-stock-iv https://leetcode.com/problems/best-time-to-buy-and-sell-stock-with-transaction-fee https://leetcode.com/problems/binary-search-tree-iterator https://leetcode.com/problems/container-with-most-water https://leetcode.com/problems/course-schedule https://leetcode.com/problems/course-schedule-ii https://leetcode.com/problems/decode-string https://leetcode.com/problems/design-add-and-search-words-data-structure https://leetcode.com/problems/design-browser-history https://leetcode.com/problems/design-circular-queue https://leetcode.com/problems/design-hashmap https://leetcode.com/problems/design-hit-counter https://leetcode.com/problems/design-tic-tac-toe https://leetcode.com/problems/distribute-money-to-maximum-children https://leetcode.com/problems/exam-room https://leetcode.com/problems/find-first-and-last-position-of-element-in-sorted-array https://leetcode.com/problems/find-k-closest-elements https://leetcode.com/problems/find-median-from-data-stream https://leetcode.com/problems/find-peak-element https://leetcode.com/problems/first-unique-character-in-a-string https://leetcode.com/problems/flatten-nested-list-iterator https://leetcode.com/problems/flood-fill https://leetcode.com/problems/group-anagrams https://leetcode.com/problems/implement-queue-using-stacks https://leetcode.com/problems/implement-trie-prefix-tree https://leetcode.com/problems/insert-delete-getrandom-o1 https://leetcode.com/problems/intersection-of-two-arrays https://leetcode.com/problems/keys-and-rooms https://leetcode.com/problems/kth-largest-element-in-an-array https://leetcode.com/problems/letter-combinations-of-a-phone-number https://leetcode.com/problems/lfu-cache https://leetcode.com/problems/longest-common-prefix https://leetcode.com/problems/longest-consecutive-sequence https://leetcode.com/problems/longest-substring-with-at-most-k-distinct-characters https://leetcode.com/problems/longest-substring-without-repeating-characters https://leetcode.com/problems/lowest-common-ancestor-of-a-binary-tree https://leetcode.com/problems/lru-cache https://leetcode.com/problems/maximize-distance-to-closest-person https://leetcode.com/problems/maximum-path-quality-of-a-graph https://leetcode.com/problems/maximum-subarray https://leetcode.com/problems/merge-intervals https://leetcode.com/problems/merge-k-sorted-lists https://leetcode.com/problems/merge-sorted-array https://leetcode.com/problems/merge-two-sorted-lists https://leetcode.com/problems/middle-of-the-linked-list https://leetcode.com/problems/min-stack https://leetcode.com/problems/minimize-maximum-component-cost https://leetcode.com/problems/move-zeroes https://leetcode.com/problems/number-of-islands https://leetcode.com/problems/permutations-ii https://leetcode.com/problems/product-of-array-except-self https://leetcode.com/problems/read-n-characters-given-read4 https://leetcode.com/problems/read-n-characters-given-read4-ii-call-multiple-times https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string https://leetcode.com/problems/remove-duplicates-from-sorted-array https://leetcode.com/problems/remove-nth-node-from-end-of-list https://leetcode.com/problems/reverse-linked-list https://leetcode.com/problems/rotate-array https://leetcode.com/problems/rotate-image https://leetcode.com/problems/rotting-oranges https://leetcode.com/problems/search-a-2d-matrix-ii https://leetcode.com/problems/serialize-and-deserialize-binary-tree https://leetcode.com/problems/set-matrix-zeroes https://leetcode.com/problems/short-encoding-of-words https://leetcode.com/problems/snapshot-array https://leetcode.com/problems/spiral-matrix https://leetcode.com/problems/string-compression https://leetcode.com/problems/subarray-product-less-than-k https://leetcode.com/problems/time-based-key-value-store https://leetcode.com/problems/top-k-frequent-elements https://leetcode.com/problems/trapping-rain-water https://leetcode.com/problems/two-sum https://leetcode.com/problems/valid-palindrome https://leetcode.com/problems/valid-parentheses https://leetcode.com/problems/valid-sudoku https://leetcode.com/problems/word-ladder https://leetcode.com/problems/word-ladder-ii https://leetcode.com/problems/word-search

Back to Apple (alt)LeetCode Index

Capital One — LeetCode Plan

This page groups Capital One-focused practice plans.

Capital One — 30 Days

Container With Most Water

Simplify Path

Binary Tree Paths

Back to Capital OneLeetCode Index

Capital One — 90 Days

Text Justification

Number Of Black Blocks

Simple Bank System

Simplify Path

Find The Length Of The Longest Common Prefix

Minimum Operations To Write The Letter Y On A Grid

Container With Most Water

Largest Rectangle In Histogram

Candy Crush

Grumpy Bookstore Owner

Brightest Position On Street

Number Of Islands

Binary Tree Paths

Monotonic Array

Longest Continuous Subarray With Absolute Diff Less Than Or Equal To Limit

Alternating Digit Sum

Back to Capital OneLeetCode Index

Capital One — 180 Days

Text Justification

Simple Bank System

Number Of Black Blocks

Simplify Path

Candy Crush

Find The Length Of The Longest Common Prefix

Largest Rectangle In Histogram

Rotating The Box

Minimum Operations To Write The Letter Y On A Grid

Container With Most Water

Minimum Time Difference

Block Placement Queries

Binary Tree Paths

Grumpy Bookstore Owner

Longest Continuous Subarray With Absolute Diff Less Than Or Equal To Limit

Brightest Position On Street

Number Of Subarrays That Match A Pattern I

Add Two Numbers

Spiral Matrix

Merge Intervals

Number Of Islands

Monotonic Array

Subarrays With K Different Integers

Restore The Array From Adjacent Pairs

Alternating Digit Sum

Number Of Adjacent Elements With The Same Color

Count Prefix And Suffix Pairs Ii

Back to Capital OneLeetCode Index

NVidia — LeetCode Plan

This page groups NVidia-focused practice plans.

NVidia — 30 Days

Special Binary String

Find The Original Array Of Prefix Xor

Merge K Sorted Lists

Lru Cache

Number Of Ways To Split Array

Back to NVidiaLeetCode Index

NVidia — 90 Days

Special Binary String

Lru Cache

Find The Original Array Of Prefix Xor

Merge K Sorted Lists

Merge Intervals

Power Of Two

Fizz Buzz

String To Integer Atoi

Valid Parentheses

Trapping Rain Water

Powx N

Missing Number

Number Of Ways To Split Array

Back to NVidiaLeetCode Index

NVidia — 180 Days

Problem List

Special Binary String

Fizz Buzz

Lru Cache

Find The Original Array Of Prefix Xor

Merge K Sorted Lists

Add Two Numbers

Search In Rotated Sorted Array

Merge Intervals

Best Time To Buy And Sell Stock

Power Of Two

Maximum Number Of Events That Can Be Attended

Two Sum

String To Integer Atoi

Valid Parentheses

Trapping Rain Water

Powx N

Reverse Linked List Ii

Copy List With Random Pointer

Reverse Linked List

Product Of Array Except Self

Missing Number

Top K Frequent Elements

Number Of Ways To Split Array

Back to NVidiaLeetCode Index

Uber — LeetCode Plan

This page groups Uber-focused practice plans.

Uber — 30 Days

Special Binary String

Find The Original Array Of Prefix Xor

Merge K Sorted Lists

Lru Cache

Number Of Ways To Split Array

Back to UberLeetCode Index

Uber — 90 Days

Number Of Islands Ii

Cherry Pickup

Longest Continuous Subarray With Absolute Diff Less Than Or Equal To Limit

Construct Quad Tree

Find The Closest Palindrome

Bus Routes

First Unique Number

Squares Of A Sorted Array

Number Of Islands

Alien Dictionary

Design In Memory File System

Insert Delete Getrandom O1

Kth Smallest Element In A Bst

Meeting Rooms Ii

Minimum Operations To Reduce An Integer To 0

Minimum Edge Reversals So Every Node Is Reachable

Text Justification

Word Search

Sliding Window Maximum

Final Prices With A Special Discount In A Shop

Letter Combinations Of A Phone Number

Simplify Path

Lru Cache

Dungeon Game

Serialize And Deserialize Binary Tree

Burst Balloons

Water And Jug Problem

Binary Tree Longest Consecutive Sequence Ii

Rotated Digits

Shortest Bridge

Verifying An Alien Dictionary

Subarrays With K Different Integers

Shortest Path In Binary Matrix

Design File System

Maximum Profit In Job Scheduling

Escape The Spreading Fire

Meeting Rooms Iii

Back to UberLeetCode Index

Uber — 180 Days

Alien Dictionary

Bus Routes

Construct Quad Tree

Number Of Islands Ii

Squares Of A Sorted Array

First Unique Number

Longest Continuous Subarray With Absolute Diff Less Than Or Equal To Limit

Cherry Pickup

The Maze

The Maze Ii

Find The Closest Palindrome

Number Of Islands

Kth Smallest Element In A Bst

My Calendar I

Word Search

Meeting Rooms Ii

Insert Delete Getrandom O1

Evaluate Division

Design In Memory File System

Shortest Bridge

Text Justification

Sliding Window Maximum

Time Based Key Value Store

Maximum Earnings From Taxi

Minimum Operations To Reduce An Integer To 0

Collect Coins In A Tree

Minimum Edge Reversals So Every Node Is Reachable

Simplify Path

Largest Rectangle In Histogram

Lru Cache

Dungeon Game

Course Schedule Ii

Word Search Ii

Basic Calculator

Burst Balloons

Random Pick With Weight

Rotated Digits

Number Of Matching Subsequences

Subarrays With K Different Integers

Shortest Path In Binary Matrix

Minimum Number Of Taps To Open To Water A Garden

Minimum Cost To Make At Least One Valid Path In A Grid

Final Prices With A Special Discount In A Shop

Rotating The Box

Brightest Position On Street

Detonate The Maximum Bombs

Add Two Numbers

Letter Combinations Of A Phone Number

Reverse Nodes In K Group

Next Permutation

Trapping Rain Water

Group Anagrams

Merge Intervals

Minimum Path Sum

Word Break

Basic Calculator Ii

Serialize And Deserialize Binary Tree

Reconstruct Itinerary

Top K Frequent Elements

Design Hit Counter

Water And Jug Problem

Shuffle An Array

Split Array Largest Sum

Add Strings

Ones And Zeroes

Random Point In Non Overlapping Rectangles

Binary Tree Longest Consecutive Sequence Ii

2 Keys Keyboard

Open The Lock

Koko Eating Bananas

Verifying An Alien Dictionary

Maximize Sum Of Array After K Negations

Largest 1 Bordered Square

Design File System

Maximum Profit In Job Scheduling

Maximum Points You Can Obtain From Cards

Leftmost Column With At Least A One

Find Critical And Pseudo Critical Edges In Minimum Spanning Tree

Find All Possible Recipes From Given Supplies

Replace Non Coprime Numbers In Array

Longest Path With Different Adjacent Characters

Escape The Spreading Fire

Count Integers In Intervals

Meeting Rooms Iii

Find The Maximum Length Of Valid Subsequence Ii

Maximum Manhattan Distance After K Changes

Back to UberLeetCode Index