-
Create LinkedList in Rust
-
Heap in Rust 2.1. Create a new class and make sure you can change how heap sorts the data
-
BST in Rust 2.2 Use the same class as above and make sure how you can change the sroting
-
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
-
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
- 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 }
- 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:
- HashMap for O(1) average time lookups — mapping a key to a node in a linked list.
- 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(binary1100). n - 1 = 11(binary1011).n & (n - 1)is1100 & 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):
- Count set bits in adjacent 2-bit chunks.
- Sum the results into 4-bit chunks.
- Sum the results into 8-bit chunks.
- Sum the results into 16-bit chunks.
- 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:
-
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 translaten.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. -
Optimal Fallback: On the rare occasion that the target CPU doesn't have a
POPCNTinstruction, 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. -
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
| Method | Performance | Iterations / Complexity | Memory Usage | Best Use Case |
|---|---|---|---|---|
| Simple Iteration | Slow | 32 (Fixed) | None | Simple to understand, educational. |
| Brian Kernighan's | Good (Variable) | k (where k is # of set bits) | None | Great for sparse inputs; good interview question. |
| Lookup Table (LUT) | Very Fast | Constant (O(1)) | ~256 bytes | Embedded systems or scenarios where memory is cheap and speed is critical. |
| Parallel (SWAR) | Very Fast | Constant (O(1)) | None | When a hardware instruction is unavailable and you can't use extra memory. |
n.count_ones() | Optimal | 1 CPU instruction | None | Almost 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
keystring is used to build a substitution map, and then themessageis 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). AHashMaplookup 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
| Aspect | Original HashMap Approach | Improved Array Approach | Why it's Better |
|---|---|---|---|
| Speed | Moderate | Very Fast | Array indexing is much faster than hashing and hash table lookups. Working with bytes (u8) avoids Unicode overhead. |
| Memory | HashMap overhead | Minimal ([u8; 128] is 128 bytes) | Lower memory footprint and better cache locality. |
| Generality | Handles any char | Assumes ASCII | The array approach is less general but is a perfect fit for problems constrained to ASCII or byte-sized characters. |
| Readability | Clear | More complex | The 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);
}
BFS (Breadth-First Search)
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) | HashMap | Operation |
|---|---|---|
| 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.
| 1 | 1 | 1 | 1 |
|---|---|---|---|
| 0 | 1 | 1 | 0 |
| 0 | 1 | 0 | 0 |
| 1 | 1 | 1 | 1 |
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
- We use shard key like female or male
- 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!
- For example you cannot upload more than 20 videos in 24 hours!
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/problemsorpython_codes.
Amazon — LeetCode Plan
This page groups Amazon-focused practice plans.
Amazon — 30 Days
Problem List
Minimum Time To Complete All Deliveries
Longest Substring Without Repeating Characters
Best Time To Buy And Sell Stock
Remove Duplicates From Sorted Array
Search In Rotated Sorted Array
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
Letter Combinations Of A Phone Number
Find The Index Of The First Occurrence In A String
Largest Rectangle In Histogram
Evaluate Reverse Polish Notation
Employees Earning More Than Their Managers
Lowest Common Ancestor Of A Binary Search Tree
Increasing Triplet Subsequence
Find K Pairs With Smallest Sums
Single Element In A Sorted Array
Managers With At Least 5 Direct Reports
Analyze User Website Visit Pattern
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 Amazon • LeetCode Index
Amazon — 90 Days
Problem List
Longest Substring Without Repeating Characters
Best Time To Buy And Sell Stock
Search In Rotated Sorted Array
Remove Duplicates From Sorted Array
Minimum Time To Complete All Deliveries
Letter Combinations Of A Phone Number
Single Element In A Sorted Array
Lowest Common Ancestor Of A Binary Tree
Binary Tree Level Order Traversal
Maximum K To Sort A Permutation
Find First And Last Position Of Element In Sorted Array
Largest Rectangle In Histogram
Populating Next Right Pointers In Each Node
Managers With At Least 5 Direct Reports
Binary Tree Zigzag Level Order Traversal
Employees Earning More Than Their Managers
Kth Largest Element In An Array
Serialize And Deserialize Binary Tree
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
Find The Index Of The First Occurrence In A String
Find K Pairs With Smallest Sums
Longest Repeating Character Replacement
Capacity To Ship Packages Within D Days
Maximum Profit In Job Scheduling
Furthest Building You Can Reach
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
Substring With Concatenation Of All Words
Remove Duplicates From Sorted List
Best Time To Buy And Sell Stock Ii
Two Sum Ii Input Array Is Sorted
Lowest Common Ancestor Of A Binary Search Tree
Number Of Connected Components In An Undirected Graph
Insert Delete Getrandom O1 Duplicates Allowed
Longest Harmonious Subsequence
Smallest Range Covering Elements From K Lists
Distribute Coins In Binary Tree
Vertical Order Traversal Of A Binary Tree
Subarrays With K Different Integers
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
Ways To Express An Integer As Sum Of Powers
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
Length Of Longest V Shaped Diagonal Segment
Remove Nth Node From End Of List
Search In Rotated Sorted Array Ii
Flatten Binary Tree To Linked List
Evaluate Reverse Polish Notation
Design Add And Search Words Data Structure
Shortest Distance From All Buildings
Increasing Triplet Subsequence
First Unique Character In A String
Longest Palindromic Subsequence
Maximum Length Of Repeated Subarray
Cheapest Flights Within K Stops
Peak Index In A Mountain Array
Shortest Subarray With Sum At Least K
Most Stones Removed With Same Row Or Column
Next Greater Node In Linked List
Customers Who Bought All Products
Remove All Adjacent Duplicates In String
Critical Connections In A Network
Sort Items By Groups Respecting Dependencies
Remove All Adjacent Duplicates In String Ii
Minimum Insertion Steps To Make A String Palindrome
Number Of Operations To Make Network Connected
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
Minimum Number Of Days To Make M Bouquets
Number Of Subsequences That Satisfy The Given Sum Condition
Count Submatrices With All Ones
Magnetic Force Between Two Balls
Customer Who Visited But Did Not Make Any Transactions
Min Cost To Connect All Points
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
Primary Department For Each Employee
Frequency Of The Most Frequent Element
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
Find The Maximum Achievable Number
Maximum Frequency Of An Element After Performing Operations I
Maximum Frequency After Subarray Operation
Find Most Frequent Vowel And Consonant
Minimum Operations To Equalize Binary String
Sum Of Perfect Square Ancestors
Back to Amazon • LeetCode Index
Amazon — 180 Days
Problem List
Longest Substring Without Repeating Characters
Best Time To Buy And Sell Stock
Lowest Common Ancestor Of A Binary Tree
Maximum Frequency After Subarray Operation
Search In Rotated Sorted Array
Find First And Last Position Of Element In Sorted Array
Analyze User Website Visit Pattern
Single Element In A Sorted Array
Remove Duplicates From Sorted Array
Capacity To Ship Packages Within D Days
Letter Combinations Of A Phone Number
Longest Repeating Character Replacement
Minimum Number Of Primes To Sum To Target
Kth Largest Element In An Array
Largest Rectangle In Histogram
Binary Tree Level Order Traversal
Best Time To Buy And Sell Stock Ii
Serialize And Deserialize Binary Tree
Binary Tree Zigzag Level Order Traversal
Populating Next Right Pointers In Each Node
Maximum K To Sort A Permutation
Minimum Time To Complete All Deliveries
Find The Index Of The First Occurrence In A String
Construct Binary Tree From Preorder And Inorder Traversal
Employees Earning More Than Their Managers
All Nodes Distance K In Binary Tree
Maximum Profit In Job Scheduling
Remove Duplicates From Sorted Array Ii
Two Sum Ii Input Array Is Sorted
First Unique Character In A String
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
Number Of Connected Components In An Undirected Graph
Vertical Order Traversal Of A Binary Tree
Check If Array Is Sorted And Rotated
Find The Median Of The Uniqueness Array
Remove Nth Node From End Of List
Convert Sorted Array To Binary Search Tree
Evaluate Reverse Polish Notation
Find K Pairs With Smallest Sums
Managers With At Least 5 Direct Reports
Peak Index In A Mountain Array
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
Remove Duplicates From Sorted List
Longest Increasing Subsequence
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
Furthest Building You Can Reach
Average Time Of Process Per Machine
Substring With Concatenation Of All Words
Lowest Common Ancestor Of A Binary Search Tree
Longest Harmonious Subsequence
Cheapest Flights Within K Stops
Subarrays With K Different Integers
Maximum Subarray Sum With One Deletion
Minimum Number Of Days To Make M Bouquets
Min Cost To Connect All Points
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
Find Minimum In Rotated Sorted Array
Intersection Of Two Linked Lists
Insert Delete Getrandom O1 Duplicates Allowed
Smallest Range Covering Elements From K Lists
Kth Largest Element In A Stream
Maximize Distance To Closest Person
Minimum Add To Make Parentheses Valid
Customers Who Bought All Products
Critical Connections In A Network
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
Minimum Cost To Reach Destination In Time
Kth Smallest Product Of Two Sorted Arrays
Rearrange Array Elements By Sign
Number Of Zero Filled Subarrays
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
Flatten Binary Tree To Linked List
Design Add And Search Words Data Structure
Binary Tree Vertical Order Traversal
Shortest Distance From All Buildings
K Th Smallest In Lexicographical Order
Flip String To Monotone Increasing
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
Find The Smallest Divisor Given A Threshold
Number Of Operations To Make Network Connected
How Many Numbers Are Smaller Than The Current Number
Maximum Sum Bst In Binary Tree
Percentage Of Users Attended A Contest
Maximum Number Of Events That Can Be Attended Ii
Primary Department For Each Employee
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
Successful Pairs Of Spells And Potions
Number Of People Aware Of A Secret
Smallest Missing Non Negative Integer After Operations
Minimum Equal Sum Of Two Arrays After Replacing Zeros
Find Missing And Repeated Values
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
Length Of Longest V Shaped Diagonal Segment
Maximum Unique Subarray Sum After Deletion
Find The Minimum Amount Of Time To Brew Potions
Maximum Total From Optimal Activation Order
Increasing Triplet Subsequence
Longest Substring With At Least K Repeating Characters
Flatten A Multilevel Doubly Linked List
Shortest Unsorted Continuous Subarray
Design Search Autocomplete System
Search In A Binary Search Tree
Insert Into A Binary Search Tree
Maximum Length Of Repeated Subarray
Find Smallest Letter Greater Than Target
All Paths From Source To Target
Shortest Subarray With Sum At Least K
Most Stones Removed With Same Row Or Column
Distribute Coins In Binary Tree
Minimum Score Triangulation Of Polygon
Lexicographically Smallest Equivalent String
Shortest Path With Alternating Colors
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
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
Minimum Operations To Reduce X To Zero
Swapping Nodes In A Linked List
The Number Of Employees Which Report To Each Employee
Minimum Number Of People To Teach
Minimum Number Of Operations To Move All Balls To Each Box
Sum Of Beauty Of All Substrings
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
Count Unreachable Pairs Of Nodes In An Undirected Graph
Smallest Number In Infinite Set
Maximum Tastiness Of Candy Basket
Minimum Operations To Reduce An Integer To 0
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
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
Maximum Number Of Distinct Elements After Operations
Search In Rotated Sorted Array Ii
Remove Duplicates From Sorted List Ii
Construct Binary Tree From Inorder And Postorder Traversal
Best Time To Buy And Sell Stock Iii
Different Ways To Add Parentheses
Longest Increasing Path In A Matrix
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
Find All Duplicates In An Array
Minimum Number Of Arrows To Burst Balloons
Minimum Moves To Equal Array Elements
Longest Palindromic Subsequence
Friend Requests Ii Who Has The Most Friends
Average Of Levels In Binary Tree
Longest Continuous Increasing Subsequence
Number Of Matching Subsequences
Reveal Cards In Increasing Order
Binary Search Tree To Greater Sum Tree
Greatest Common Divisor Of Strings
Minimum Cost To Connect Sticks
Sort Items By Groups Respecting Dependencies
Minimum Cost To Move Chips To The Same Position
Count Number Of Nice Subarrays
Count Servers That Communicate
Shortest Path In A Grid With Obstacles Elimination
Find Numbers With Even Number Of Digits
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
Longest Subarray Of 1s After Deleting One Element
Maximum Nesting Depth Of The Parentheses
Lexicographically Smallest String After Applying Operations
Minimum Deletions To Make Character Frequencies Unique
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
Check If All The Integers In A Range Are Covered
Nearest Exit From Entrance In Maze
Painting A Grid With Three Different Colors
Last Day Where You Can Still Cross
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
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
Find Resultant Array After Removing Anagrams
Sum Of Total Strength Of Wizards
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
Maximum Difference By Remapping A Digit
Maximum Beauty Of An Array After Applying Operation
Count Complete Subarrays In An Array
Distribute Candies Among Children Ii
Maximum Size Of A Set After Removals
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
Minimum Pair Removal To Sort Array I
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 Amazon • LeetCode Index
Apple — LeetCode Plan
This page groups Apple-focused practice plans.
Apple — 30 Days
Maximum Path Quality Of A Graph
Serialize And Deserialize Binary Tree
Remove All Adjacent Duplicates In String
Back to Apple • LeetCode Index
Apple — 90 Days
Remove All Adjacent Duplicates In String
Find First And Last Position Of Element In Sorted Array
Best Time To Buy And Sell Stock
Best Time To Buy And Sell Stock Ii
Design Add And Search Words Data Structure
Serialize And Deserialize Binary Tree
Maximum Path Quality Of A Graph
Longest Substring Without Repeating Characters
Remove Duplicates From Sorted Array
Lowest Common Ancestor Of A Binary Tree
Best Time To Buy And Sell Stock With Transaction Fee
Distribute Money To Maximum Children
Minimize Maximum Component Cost
Back to Apple • LeetCode Index
Apple — 180 Days
Best Time To Buy And Sell Stock
Best Time To Buy And Sell Stock Ii
Find First And Last Position Of Element In Sorted Array
Best Time To Buy And Sell Stock With Transaction Fee
Longest Substring Without Repeating Characters
Letter Combinations Of A Phone Number
Remove All Adjacent Duplicates In String
Remove Duplicates From Sorted Array
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
Lowest Common Ancestor Of A Binary Tree
Serialize And Deserialize Binary Tree
Maximum Path Quality Of A Graph
Distribute Money To Maximum Children
Remove Nth Node From End Of List
Best Time To Buy And Sell Stock Iii
Longest Substring With At Most K Distinct Characters
First Unique Character In A String
Maximize Distance To Closest Person
Minimize Maximum Component Cost
Back to Apple • LeetCode Index
Google — LeetCode Plan
This page groups Google-focused practice plans.
Google — 30 Days
Problem List
Best Time To Buy And Sell Stock
Find The Index Of The First Occurrence In A String
Number Of Visible People In A Queue
Longest Substring Without Repeating Characters
Minimum Number Of Increments On Subarrays To Form A Target Array
Calculate Money In Leetcode Bank
Remove Duplicates From Sorted Array
Find First And Last Position Of Element In Sorted Array
Employees Earning More Than Their Managers
Longest Increasing Subsequence
Next Greater Numerically Balanced Number
Make Array Elements Equal To Zero
Smallest Number With All Set Bits
Search In Rotated Sorted Array
Lowest Common Ancestor Of A Binary Tree
Final Value Of Variable After Performing Operations
Find Resultant Array After Removing Anagrams
Maximum Frequency Of An Element After Performing Operations I
Adjacent Increasing Subarrays Detection I
Remove Duplicates From Sorted List
Largest Rectangle In Histogram
Binary Tree Level Order Traversal
Populating Next Right Pointers In Each Node
Find Minimum In Rotated Sorted Array Ii
Intersection Of Two Linked Lists
Two Sum Ii Input Array Is Sorted
Kth Largest Element In An Array
Increasing Triplet Subsequence
Single Element In A Sorted Array
Longest Continuous Increasing Subsequence
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
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
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 Google • LeetCode Index
Google — 90 Days
Best Time To Buy And Sell Stock
Longest Substring Without Repeating Characters
Find The Index Of The First Occurrence In A String
Number Of Visible People In A Queue
Search In Rotated Sorted Array
Remove Duplicates From Sorted Array
Find N Unique Integers Sum Up To Zero
Recyclable And Low Fat Products
Employees Earning More Than Their Managers
Kth Largest Element In An Array
Longest Increasing Subsequence
Find First And Last Position Of Element In Sorted Array
Minimum Number Of Increments On Subarrays To Form A Target Array
Binary Tree Zigzag Level Order Traversal
Longest Repeating Character Replacement
Single Element In A Sorted Array
Next Greater Numerically Balanced Number
Largest Rectangle In Histogram
Find All Numbers Disappeared In An Array
Peak Index In A Mountain Array
Count Submatrices With All Ones
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
Letter Combinations Of A Phone Number
Remove Nth Node From End Of List
Binary Tree Level Order Traversal
Best Time To Buy And Sell Stock Ii
Intersection Of Two Linked Lists
Lowest Common Ancestor Of A Binary Tree
The Earliest Moment When Everyone Become Friends
Convert Integer To The Sum Of Two No Zero Integers
Longest Subarray Of 1s After Deleting One Element
Average Time Of Process Per Machine
Check If Array Is Sorted And Rotated
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
Remove Duplicates From Sorted Array Ii
Remove Duplicates From Sorted List
Construct Binary Tree From Preorder And Inorder Traversal
Populating Next Right Pointers In Each Node
Find Minimum In Rotated Sorted Array Ii
Two Sum Ii Input Array Is Sorted
Serialize And Deserialize Binary Tree
Increasing Triplet Subsequence
Longest Word In Dictionary Through Deleting
Longest Continuous Increasing Subsequence
Capacity To Ship Packages Within D Days
Greatest Common Divisor Of Strings
Shortest Path In Binary Matrix
Path With Maximum Minimum Value
Count Square Submatrices With All Ones
Find The Smallest Divisor Given A Threshold
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
Rearrange Array Elements By Sign
Number Of People Aware Of A Secret
The Latest Time To Catch A Bus
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
Remove Duplicates From Sorted List Ii
Convert Sorted Array To Binary Search Tree
Evaluate Reverse Polish Notation
Best Time To Buy And Sell Stock With Cooldown
Longest Increasing Path In A Matrix
First Unique Character In A String
Queue Reconstruction By Height
Minimum Absolute Difference In Bst
Managers With At Least 5 Direct Reports
Classes With At Least 5 Students
Friend Requests Ii Who Has The Most Friends
Design Search Autocomplete System
Binary Number With Alternating Bits
Number Of Matching Subsequences
Shortest Path Visiting All Nodes
All Nodes Distance K In Binary Tree
Minimum Number Of Refueling Stops
X Of A Kind In A Deck Of Cards
Satisfiability Of Equality Equations
Delete Nodes And Return Forest
Highest Grade For Each Student
Critical Connections In A Network
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
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
Number Of Students Unable To Eat Lunch
Check If Number Is A Sum Of Powers Of Three
Frequency Of The Most Frequent Element
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
Number Of Zero Filled Subarrays
Range Product Queries Of Powers
Left And Right Sum Differences
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
Maximum Frequency Of An Element After Performing Operations Ii
Adjacent Increasing Subarrays Detection Ii
Maximum Subarray With Equal Products
Check If Digits Are Equal In String After Operations I
Minimum Pair Removal To Sort Array I
Partition Array Into K Distinct Groups
Subsequence Sum After Capping Elements
Sum Of Perfect Square Ancestors
Lexicographically Smallest Permutation Greater Than Target
Back to Google • LeetCode Index
Google — 180 Days
Best Time To Buy And Sell Stock
Longest Substring Without Repeating Characters
Number Of Visible People In A Queue
Remove Duplicates From Sorted Array
Search In Rotated Sorted Array
Find The Index Of The First Occurrence In A String
Recyclable And Low Fat Products
Largest Rectangle In Histogram
Longest Repeating Character Replacement
Best Time To Buy And Sell Stock Ii
Longest Increasing Subsequence
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
Kth Largest Element In An Array
Next Special Palindrome Number
Two Sum Ii Input Array Is Sorted
Peak Index In A Mountain Array
Binary Tree Zigzag Level Order Traversal
Employees Earning More Than Their Managers
Path With Maximum Minimum Value
Find N Unique Integers Sum Up To Zero
Remove Duplicates From Sorted List
Lowest Common Ancestor Of A Binary Tree
K Th Smallest In Lexicographical Order
Maximum Number Of Events That Can Be Attended
Rearrange Array Elements By Sign
Find Minimum In Rotated Sorted Array
Intersection Of Two Linked Lists
Find All Numbers Disappeared In An Array
Longest Harmonious Subsequence
Delete Nodes And Return Forest
Shortest Path In A Grid With Obstacles Elimination
Check If Array Is Sorted And Rotated
Remove Duplicates From Sorted List Ii
Binary Tree Level Order Traversal
Construct Binary Tree From Preorder And Inorder Traversal
Serialize And Deserialize Binary Tree
Capacity To Ship Packages Within D Days
Count Square Submatrices With All Ones
Minimum Number Of Days To Make M Bouquets
Minimum Number Of Increments On Subarrays To Form A Target Array
Minimum Time To Finish The Race
Find Missing And Repeated Values
Substring With Concatenation Of All Words
Remove Duplicates From Sorted Array Ii
Convert Sorted Array To Binary Search Tree
Managers With At Least 5 Direct Reports
Vertical Order Traversal Of A Binary Tree
Replace Employee Id With The Unique Identifier
Longest Subarray Of 1s After Deleting One Element
Calculate Money In Leetcode Bank
Maximum Score From Removing Substrings
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
Evaluate Reverse Polish Notation
Find Minimum In Rotated Sorted Array Ii
Design Add And Search Words Data Structure
Increasing Triplet Subsequence
First Unique Character In A String
Find All Duplicates In An Array
Minimum Number Of K Consecutive Bit Flips
Greatest Common Divisor Of Strings
Shortest Path In Binary Matrix
Count Submatrices With All Ones
Frequency Of The Most Frequent Element
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
Range Product Queries Of Powers
Minimum Operations To Make The Integer Zero
Divide Array Into Arrays With Max Difference
Find The Original Typed String I
Find The Original Typed String Ii
Search In Rotated Sorted Array Ii
Best Time To Buy And Sell Stock Iii
Best Time To Buy And Sell Stock With Cooldown
Find K Pairs With Smallest Sums
Cheapest Flights Within K Stops
Shortest Path Visiting All Nodes
The Earliest Moment When Everyone Become Friends
Count Number Of Nice Subarrays
Find The Smallest Divisor Given A Threshold
Convert Integer To The Sum Of Two No Zero Integers
Minimum Number Of Taps To Open To Water A Garden
Find Lucky Integer In An Array
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
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
Find The Maximum Achievable Number
Find The Maximum Length Of Valid Subsequence I
Maximize Subarrays After Removing One Conflicting Pair
Minimum Operations To Make Array Elements Zero
Flatten Binary Tree To Linked List
Populating Next Right Pointers In Each Node
Different Ways To Add Parentheses
Minimum Absolute Difference In Bst
Design Search Autocomplete System
Longest Continuous Increasing Subsequence
Number Of Matching Subsequences
Convert Binary Number In A Linked List To Integer
Maximum Sum Bst In Binary Tree
Maximum Points You Can Obtain From Cards
The Number Of Employees Which Report To Each Employee
Minimum Interval To Include Each Query
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
Maximum Fruits Harvested After At Most K Steps
Minimum Weighted Subgraph With The Required Paths
Find Resultant Array After Removing Anagrams
Ways To Express An Integer As Sum Of Powers
Find Words Containing Character
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
Minimum Pair Removal To Sort Array I
Binary Tree Preorder Traversal
Best Time To Buy And Sell Stock Iv
Lowest Common Ancestor Of A Binary Search Tree
Longest Increasing Path In A Matrix
Count Numbers With Unique Digits
Kth Smallest Element In A Sorted Matrix
Queue Reconstruction By Height
Reconstruct Original Digits From English
Longest Word In Dictionary Through Deleting
Shortest Unsorted Continuous Subarray
Delete Operation For Two Strings
Classes With At Least 5 Students
Smallest Range Covering Elements From K Lists
Best Time To Buy And Sell Stock With Transaction Fee
Find Smallest Letter Greater Than Target
Maximize Distance To Closest Person
X Of A Kind In A Deck Of Cards
Reveal Cards In Increasing Order
Subarrays With K Different Integers
Customers Who Bought All Products
Maximum Nesting Depth Of Two Valid Parentheses Strings
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
Time Needed To Inform All Employees
Number Of Subsequences That Satisfy The Given Sum Condition
Magnetic Force Between Two Balls
Min Cost To Connect All Points
Lowest Common Ancestor Of A Binary Tree Iii
Sum Of Absolute Differences In A Sorted Array
Number Of Students Unable To Eat Lunch
Minimum Number Of People To Teach
Minimum Number Of Operations To Move All Balls To Each Box
Sum Of Beauty Of All Substrings
Finding Pairs With A Certain Sum
The Earliest And Latest Rounds Where Players Compete
Number Of Ways To Arrive At Destination
Partition Array Into Two Arrays To Minimize Sum Difference
Count Number Of Maximum Bitwise Or Subsets
Step By Step Directions From A Binary Tree Node To Another
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
Left And Right Sum Differences
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
Lexicographically Minimum String After Removing Stars
Maximum Total Damage With Spell Casting
Find The Maximum Length Of Valid Subsequence Ii
Delete Nodes From Linked List Present In Array
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
Minimum Swaps To Sort By Digit Sum
Find Weighted Median Node In 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
Smallest Rectangle Enclosing Black Pixels
Binary Tree Vertical Order Traversal
Maximum Product Of Word Lengths
Maximum Xor Of Two Numbers In An Array
Flatten A Multilevel Doubly Linked List
Number Of Segments In A String
Minimum Moves To Equal Array Elements
Longest Palindromic Subsequence
Friend Requests Ii Who Has The Most Friends
Number Of Longest Increasing Subsequence
Maximum Sum Of 3 Non Overlapping Subarrays
Binary Number With Alternating Bits
Search In A Binary Search Tree
Maximum Length Of Repeated Subarray
All Nodes Distance K In Binary Tree
Minimum Number Of Refueling Stops
All Possible Full Binary Trees
Minimum Add To Make Parentheses Valid
Satisfiability Of Equality Equations
Pairs Of Songs With Total Durations Divisible By 60
Partition Array For Maximum Sum
Lexicographically Smallest Equivalent String
Highest Grade For Each Student
Minimum Cost Tree From Leaf Values
Critical Connections In A Network
Tiling A Rectangle With The Fewest Squares
Minimum Moves To Move A Box To Their Target Location
Maximum Candies You Can Get From Boxes
Decompress Run Length Encoded List
Delete Leaves With A Given Value
Number Of Steps To Reduce A Number To Zero
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
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
Count Odd Numbers In An Interval Range
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
Percentage Of Users Attended A Contest
Minimum Operations To Reduce X To Zero
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
Maximum Value At A Given Index In A Bounded Array
Determine Whether Matrix Can Be Obtained By Rotation
Unique Length 3 Palindromic Subsequences
Delete Duplicate Folders In System
Find Greatest Common Divisor Of Array
Maximum Product Of The Length Of Two Palindromic Subsequences
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
Partition Array Such That Maximum Difference Is K
Successful Pairs Of Spells And Potions
Minimum Score After Removals On A Tree
Number Of Zero Filled Subarrays
Number Of Unique Subjects Taught By Each Teacher
Minimum Replacements To Sort The Array
Minimum Recolors To Get K Consecutive Black Blocks
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
Return Length Of Arguments Passed
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
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
Find The Maximum Number Of Fruits Collected
Maximum Subarray With Equal Products
Check If Digits Are Equal In String After Operations I
Maximum Unique Subarray Sum After Deletion
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
Subsequence Sum After Capping Elements
Sum Of Perfect Square Ancestors
Lexicographically Smallest Permutation Greater Than Target
Back to Google • LeetCode Index
Microsoft — LeetCode Plan
This page groups Microsoft-focused practice plans.
Microsoft — 30 Days
Count The Number Of Infection Sequences
Minimum Number Of Steps To Make Two Strings Anagram
Longest Substring Without Repeating Characters
Remove Duplicates From Sorted Array
Calculate Money In Leetcode Bank
Minimum Operations To Reduce An Integer To 0
Smallest Number With All Set Bits
Best Time To Buy And Sell Stock
Find Minimum In Rotated Sorted Array
First Unique Character In A String
Minimum Difficulty Of A Job Schedule
Check If The Sentence Is Pangram
Minimum Edge Reversals So Every Node Is Reachable
The Two Sneaky Numbers Of Digitville
Back to Microsoft • LeetCode Index
Microsoft — 90 Days
Longest Substring Without Repeating Characters
Best Time To Buy And Sell Stock
Remove Duplicates From Sorted Array
Search In Rotated Sorted Array
Count The Number Of Infection Sequences
Minimum Operations To Reduce An Integer To 0
Minimum Operations To Make Array Equal To Target
Remove Nth Node From End Of List
Two Sum Ii Input Array Is Sorted
Lowest Common Ancestor Of A Binary Tree
First Unique Character In A String
Calculate Money In Leetcode Bank
Find The Index Of The First Occurrence In A String
Largest Rectangle In Histogram
Populating Next Right Pointers In Each Node
Find Minimum In Rotated Sorted Array
Longest Repeating Character Replacement
Convert Integer To The Sum Of Two No Zero Integers
Minimum Number Of Steps To Make Two Strings Anagram
Average Time Of Process Per Machine
Minimum Initial Energy To Finish Tasks
Binary Tree Zigzag Level Order Traversal
Best Time To Buy And Sell Stock Ii
Evaluate Reverse Polish Notation
Longest Increasing Subsequence
Longest Substring With At Least K Repeating Characters
Find All Duplicates In An Array
Single Element In A Sorted Array
Subarrays With K Different Integers
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
Find First And Last Position Of Element In Sorted Array
Binary Tree Level Order Traversal
Best Time To Buy And Sell Stock Iii
Binary Tree Preorder Traversal
Kth Largest Element In An Array
Serialize And Deserialize Binary Tree
Find K Pairs With Smallest Sums
Flatten A Multilevel Doubly Linked List
Managers With At Least 5 Direct Reports
Insert Into A Binary Search Tree
Cheapest Flights Within K Stops
Minimum Number Of Refueling Stops
Minimum Score Triangulation Of Polygon
Shortest Path In Binary Matrix
Count Servers That Communicate
Minimum Difficulty Of A Job Schedule
Minimum Value To Get Positive Step By Step Sum
Final Prices With A Special Discount In A Shop
Longest Subarray Of 1s After Deleting One Element
Find The Winner Of An Array Game
Customer Who Visited But Did Not Make Any Transactions
Primary Department For Each Employee
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
Back to Microsoft • LeetCode Index
Microsoft — 180 Days
Longest Substring Without Repeating Characters
Best Time To Buy And Sell Stock
Remove Duplicates From Sorted Array
Search In Rotated Sorted Array
Minimum Edge Reversals So Every Node Is Reachable
Largest Rectangle In Histogram
Minimum Operations To Reduce An Integer To 0
Find The Index Of The First Occurrence In A String
Find First And Last Position Of Element In Sorted Array
Single Element In A Sorted Array
Count The Number Of Infection Sequences
Lowest Common Ancestor Of A Binary Tree
Longest Repeating Character Replacement
Count Palindromic Subsequences
Remove Nth Node From End Of List
Binary Tree Level Order Traversal
Best Time To Buy And Sell Stock Ii
Find Minimum In Rotated Sorted Array
Serialize And Deserialize Binary Tree
Minimum Difficulty Of A Job Schedule
Binary Tree Zigzag Level Order Traversal
Employees Earning More Than Their Managers
Longest Increasing Subsequence
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
Populating Next Right Pointers In Each Node
Two Sum Ii Input Array Is Sorted
First Unique Character In A String
Find All Duplicates In An Array
Peak Index In A Mountain Array
Maximum Number Of Events That Can Be Attended
Minimum Value To Get Positive Step By Step Sum
Average Time Of Process Per Machine
Calculate Money In Leetcode Bank
Maximum Difference Between Even And Odd Frequency I
Evaluate Reverse Polish Notation
Kth Largest Element In An Array
Managers With At Least 5 Direct Reports
Subarrays With K Different Integers
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
Find The Original Typed String Ii
Remove Duplicates From Sorted Array Ii
Convert Sorted Array To Binary Search Tree
Best Time To Buy And Sell Stock Iii
Intersection Of Two Linked Lists
Longest Substring With At Most K Distinct Characters
Longest Substring With At Least K Repeating Characters
K Th Smallest In Lexicographical Order
Friend Requests Ii Who Has The Most Friends
Kth Largest Element In A Stream
All Nodes Distance K In Binary Tree
Vertical Order Traversal Of A Binary Tree
Greatest Common Divisor Of Strings
Shortest Path In Binary Matrix
Maximum Profit In Job Scheduling
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
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
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
Construct Binary Tree From Preorder And Inorder Traversal
Populating Next Right Pointers In Each Node Ii
Binary Tree Preorder Traversal
Design Add And Search Words Data Structure
Lowest Common Ancestor Of A Binary Search Tree
Binary Tree Vertical Order Traversal
Find K Pairs With Smallest Sums
Flatten A Multilevel Doubly Linked List
Find All Numbers Disappeared In An Array
Longest Palindromic Subsequence
Customer Placing The Largest Number Of Orders
Classes With At Least 5 Students
Insert Into A Binary Search Tree
Best Time To Buy And Sell Stock With Transaction Fee
Cheapest Flights Within K Stops
Minimum Number Of Refueling Stops
Check Completeness Of A Binary Tree
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
Minimum Swaps To Make Strings Equal
Count Number Of Nice Subarrays
Count Servers That Communicate
Count Negative Numbers In A Sorted Matrix
Count Good Nodes In Binary Tree
Reorder Routes To Make All Paths Lead To The City Zero
Count Odd Numbers In An Interval Range
Min Cost To Connect All Points
Delete Duplicate Folders In System
Partition Array According To Given Pivot
Find Resultant Array After Removing Anagrams
Successful Pairs Of Spells And Potions
Number Of People Aware Of A Secret
Number Of Zero Filled Subarrays
Longest Subarray With Maximum Bitwise And
Find The Original Array Of Prefix Xor
Count Subarrays With Fixed Bounds
Minimum Cost To Make Array Equal
Maximize Greatness Of An Array
Minimize The Maximum Difference Of Pairs
Check If Object Instance Of Class
Find The Maximum Achievable Number
Insert Greatest Common Divisors In Linked List
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
Maximize Subarrays After Removing One Conflicting Pair
Transform Array To All Equal Elements
Back to Microsoft • LeetCode Index
Facebook — LeetCode Plan
This page groups Facebook-focused practice plans.
Facebook — 30 Days
Minimum Remove To Make Valid Parentheses
Kth Largest Element In An Array
Binary Tree Vertical Order Traversal
Lowest Common Ancestor Of A Binary Tree
Lowest Common Ancestor Of A Binary Tree Iii
Remove Duplicates From Sorted Array
Best Time To Buy And Sell Stock
Remove Nth Node From End Of List
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
Find First And Last Position Of Element In Sorted Array
Convert Binary Search Tree To Sorted Doubly Linked List
Binary Tree Level Order Traversal
Intersection Of Two Linked Lists
Closest Binary Search Tree Value
Kth Smallest Element In A Sorted Matrix
Longest Repeating Character Replacement
Insert Into A Sorted Circular Linked List
Minimum Add To Make Parentheses Valid
Capacity To Ship Packages Within D Days
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 Facebook • LeetCode Index
Facebook — 90 Days
Minimum Remove To Make Valid Parentheses
Kth Largest Element In An Array
Lowest Common Ancestor Of A Binary Tree
Binary Tree Vertical Order Traversal
Lowest Common Ancestor Of A Binary Tree Iii
Shortest Path In Binary Matrix
Best Time To Buy And Sell Stock
Find First And Last Position Of Element In Sorted Array
All Nodes Distance K In Binary Tree
Minimum Add To Make Parentheses Valid
Dot Product Of Two Sparse Vectors
Count Nodes Equal To Average Of Subtree
Longest Substring Without Repeating Characters
Remove Nth Node From End Of List
Vertical Order Traversal Of A Binary Tree
Moving Average From Data Stream
Insert Into A Sorted Circular Linked List
Closest Binary Search Tree Value
Remove Duplicates From Sorted Array
Best Time To Buy And Sell Stock Ii
Convert Binary Search Tree To Sorted Doubly Linked List
Missing Element In Sorted Array
Remove All Adjacent Duplicates In String Ii
Kids With The Greatest Number Of Candies
Populating Next Right Pointers In Each Node
Kth Smallest Element In A Sorted Matrix
Longest Repeating Character Replacement
Capacity To Ship Packages Within D Days
Remove All Adjacent Duplicates In String
Best Time To Buy And Sell Stock Using Strategy
Single Element In A Sorted Array
Managers With At Least 5 Direct Reports
Check Completeness Of A Binary Tree
Count Unguarded Cells In The Grid
Search In Rotated Sorted Array
Largest Rectangle In Histogram
Longest Increasing Path In A Matrix
Construct Binary Tree From String
Peak Index In A Mountain Array
Lowest Common Ancestor Of Deepest Leaves
Shortest Path In A Grid With Obstacles Elimination
Minimum Time To Collect All Apples In A Tree
Minimum Operations To Make The Integer Zero
Count Elements With Maximum Frequency
Binary Tree Level Order Traversal
Binary Tree Level Order Traversal Ii
Flatten Binary Tree To Linked List
Best Time To Buy And Sell Stock Iii
Intersection Of Two Linked Lists
Two Sum Ii Input Array Is Sorted
Lowest Common Ancestor Of A Binary Search Tree
Serialize And Deserialize Binary Tree
Shortest Distance From All Buildings
Friend Requests Ii Who Has The Most Friends
Minimum Score Triangulation Of Polygon
User Activity For The Past 30 Days I
Find Words That Can Be Formed By Characters
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 Facebook • LeetCode Index
Facebook — 180 Days
Minimum Remove To Make Valid Parentheses
Kth Largest Element In An Array
Binary Tree Vertical Order Traversal
Lowest Common Ancestor Of A Binary Tree
Lowest Common Ancestor Of A Binary Tree Iii
Best Time To Buy And Sell Stock
Shortest Path In Binary Matrix
Dot Product Of Two Sparse Vectors
Find First And Last Position Of Element In Sorted Array
Minimum Add To Make Parentheses Valid
Vertical Order Traversal Of A Binary Tree
Moving Average From Data Stream
Longest Substring Without Repeating Characters
All Nodes Distance K In Binary Tree
Count Nodes Equal To Average Of Subtree
Remove Nth Node From End Of List
Remove Duplicates From Sorted Array
Insert Into A Sorted Circular Linked List
Closest Binary Search Tree Value
Missing Element In Sorted Array
Kth Smallest Element In A Sorted Matrix
Search In Rotated Sorted Array
Convert Binary Search Tree To Sorted Doubly Linked List
Check Completeness Of A Binary Tree
Remove All Adjacent Duplicates In String Ii
Peak Index In A Mountain Array
Capacity To Ship Packages Within D Days
Best Time To Buy And Sell Stock Iii
Populating Next Right Pointers In Each Node
Single Element In A Sorted Array
Binary Tree Level Order Traversal
Best Time To Buy And Sell Stock Ii
Longest Repeating Character Replacement
Minimum Deletions For At Most K Distinct Characters
Remove All Adjacent Duplicates In String
Shortest Distance From All Buildings
Longest Increasing Path In A Matrix
Construct Binary Tree From String
Managers With At Least 5 Direct Reports
Kids With The Greatest Number Of Candies
Find The Index Of The First Occurrence In A String
Largest Rectangle In Histogram
Longest Increasing Subsequence
Product Of Two Run Length Encoded Arrays
Maximum Difference By Remapping A Digit
Letter Combinations Of A Phone Number
Binary Tree Zigzag Level Order Traversal
Lowest Common Ancestor Of A Binary Search Tree
Serialize And Deserialize Binary Tree
Two Sum Ii Input Array Is Sorted
Maximum Number Of Events That Can Be Attended
Minimum Time To Collect All Apples In A Tree
Frequency Of The Most Frequent Element
Largest Color Value In A Directed Graph
Minimize The Maximum Difference Of Pairs
Distribute Candies Among Children Ii
Best Time To Buy And Sell Stock Using Strategy
Search In Rotated Sorted Array Ii
Intersection Of Two Linked Lists
Increasing Triplet Subsequence
Customers Who Bought All Products
Maximum Level Sum Of A Binary Tree
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
Recyclable And Low Fat Products
Sum Of Beauty Of All Substrings
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
Construct Binary Tree From Preorder And Inorder Traversal
Binary Tree Level Order Traversal Ii
Flatten Binary Tree To Linked List
Populating Next Right Pointers In Each Node Ii
Find Minimum In Rotated Sorted Array
Employees Earning More Than Their Managers
Friend Requests Ii Who Has The Most Friends
Maximum Sum Of 3 Non Overlapping Subarrays
Number Of Matching Subsequences
Smallest Subtree With All The Deepest Nodes
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
Maximum Sum Bst In Binary Tree
Maximum Points You Can Obtain From Cards
Find Minimum Time To Finish All Jobs
Shortest Path In A Hidden Grid
Remove All Occurrences Of A Substring
Check If A Parentheses String Can Be Valid
Find All K Distant Indices In An Array
Successful Pairs Of Spells And Potions
Minimum Operations To Make The Integer Zero
Find The Minimum Amount Of Time To Brew Potions
Remove Duplicates From Sorted Array Ii
Remove Duplicates From Sorted List
Binary Tree Longest Consecutive Sequence
Find K Pairs With Smallest Sums
First Unique Character In A String
Maximum Xor Of Two Numbers In An Array
Flatten A Multilevel Doubly Linked List
Longest Uncommon Subsequence I
Longest Harmonious Subsequence
Smallest Range Covering Elements From K Lists
Average Of Levels In Binary Tree
Cheapest Flights Within K Stops
All Paths From Source To Target
Most Stones Removed With Same Row Or Column
Construct Binary Search Tree From Preorder Traversal
Sum Of Root To Leaf Binary Numbers
Minimum Score Triangulation Of Polygon
Greatest Common Divisor Of Strings
User Activity For The Past 30 Days I
Find Words That Can Be Formed By Characters
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
Count Negative Numbers In A Sorted Matrix
Replace Employee Id With The Unique Identifier
Minimum Number Of Days To Make M Bouquets
Clone Binary Tree With Random Pointer
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
Check If Array Is Sorted And Rotated
Primary Department For Each Employee
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
Maximum Alternating Subsequence Sum
Painting A Grid With Three Different Colors
Maximum Difference Between Increasing Elements
Next Greater Numerically Balanced Number
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
Smallest Number In Infinite Set
Number Of Zero Filled Subarrays
Smallest Subarrays With Maximum Bitwise Or
Number Of Pairs Satisfying Inequality
Merge Two 2d Arrays By Summing Values
Find The Prefix Common Array Of Two Arrays
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
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
Partition Array Into Two Equal Product Subsets
Compute Decimal Representation
Back to Facebook • LeetCode Index
Netflix — LeetCode Plan
This page groups Netflix-focused practice plans.
Netflix — 30 Days
Problem List
Back to Netflix • LeetCode Index
Netflix — 90 Days
Longest Substring Without Repeating Characters
Back to Netflix • LeetCode Index
Netflix — 180 Days
Longest Substring Without Repeating Characters
Back to Netflix • LeetCode 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
Back to Capital One • LeetCode Index
Capital One — 90 Days
Find The Length Of The Longest Common Prefix
Minimum Operations To Write The Letter Y On A Grid
Largest Rectangle In Histogram
Longest Continuous Subarray With Absolute Diff Less Than Or Equal To Limit
Back to Capital One • LeetCode Index
Capital One — 180 Days
Find The Length Of The Longest Common Prefix
Largest Rectangle In Histogram
Minimum Operations To Write The Letter Y On A Grid
Longest Continuous Subarray With Absolute Diff Less Than Or Equal To Limit
Number Of Subarrays That Match A Pattern I
Subarrays With K Different Integers
Restore The Array From Adjacent Pairs
Number Of Adjacent Elements With The Same Color
Count Prefix And Suffix Pairs Ii
Back to Capital One • LeetCode Index
NVidia — LeetCode Plan
This page groups NVidia-focused practice plans.
NVidia — 30 Days
Find The Original Array Of Prefix Xor
Back to NVidia • LeetCode Index
NVidia — 90 Days
Find The Original Array Of Prefix Xor
Back to NVidia • LeetCode Index
NVidia — 180 Days
Problem List
Find The Original Array Of Prefix Xor
Search In Rotated Sorted Array
Best Time To Buy And Sell Stock
Maximum Number Of Events That Can Be Attended
Back to NVidia • LeetCode Index
Uber — LeetCode Plan
This page groups Uber-focused practice plans.
Uber — 30 Days
Find The Original Array Of Prefix Xor
Back to Uber • LeetCode Index
Uber — 90 Days
Longest Continuous Subarray With Absolute Diff Less Than Or Equal To Limit
Minimum Operations To Reduce An Integer To 0
Minimum Edge Reversals So Every Node Is Reachable
Final Prices With A Special Discount In A Shop
Letter Combinations Of A Phone Number
Serialize And Deserialize Binary Tree
Binary Tree Longest Consecutive Sequence Ii
Subarrays With K Different Integers
Shortest Path In Binary Matrix
Maximum Profit In Job Scheduling
Back to Uber • LeetCode Index
Uber — 180 Days
Longest Continuous Subarray With Absolute Diff Less Than Or Equal To Limit
Minimum Operations To Reduce An Integer To 0
Minimum Edge Reversals So Every Node Is Reachable
Largest Rectangle In Histogram
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
Letter Combinations Of A Phone Number
Serialize And Deserialize Binary Tree
Random Point In Non Overlapping Rectangles
Binary Tree Longest Consecutive Sequence Ii
Maximize Sum Of Array After K Negations
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
Find The Maximum Length Of Valid Subsequence Ii
Maximum Manhattan Distance After K Changes
Back to Uber • LeetCode Index