AlgoMonster - LeetCode Top Questions FAANG

Ace your homework & exams now with Quizwiz!

Find the Celebrity: Suppose you are at a party with n people (labeled from 0 to n - 1), and among them, there may exist one celebrity. The definition of a celebrity is that all the other n - 1 people know them, but they do not know any of them except themselves. You are given a helper function bool knows(a, b) which returns true if a knows b. Implement a function int findCelebrity(n), your function should minimize the number of calls to knows.

Array

First Missing Positive: Given an unsorted integer array nums, find the smallest missing positive integer.

Array

Game of Life: According to the Wikipedia's article: "The Game of Life, also known simply as Life, is a cellular automaton devised by the British mathematician John Horton Conway in 1970." Write a function to compute the next state (after one update) of the board given its current state.

Array

Insert Interval: Given a set of non-overlapping intervals, insert a new interval into the intervals (merge if necessary).

Array

Merge Sorted Array: Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Array

Next Permutation: Implement next permutation, which rearranges numbers into the lexicographically next greater permutation of numbers.

Array

Pascal's Triangle: Given a non-negative integer numRows, generate the first numRows of Pascal's triangle.

Array

Product of Array Except Self: Given an array nums of n integers where n > 1, return an array output such that output[i] is equal to the product of all the elements of nums except nums[i].

Array

Rotate Image: You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).

Array

Set Matrix Zeroes: Given a m x n matrix, if an element is 0, set its entire row and column to 0. Do it in-place.

Array

Spiral Matrix: Given an m x n matrix, return all elements of the matrix in spiral order.

Array

Two Sum: Given an array of integers, return indices of the two numbers such that they add up to a specific target.

Array, Hash Table

3 Sum: Given an array nums of n integers, find all unique triplets in the array which gives the sum of zero.

Arrays, Two Pointers: Sort the array. Pick a stationary pointer, then perform 2 pointers on the remaining elements. If sum == target: add 3 integers to result list. If sum < target, increment L-pointer. If sum > target, decrement R-pointer. Repeat until L/R pointers cross. Skip duplicates. Return result.

Combination Sum: Given a set of candidate numbers (candidates) and a target number (target), find all unique combinations in candidates where the candidate numbers sum to target.

Backtracking

Generate Parentheses: Given n pairs of parentheses, write a function to generate all combinations of well-formed parentheses.

Backtracking

Letter Combinations of a Phone Number: Given a string containing digits from 2-9 inclusive, return all possible letter combinations that the number could represent.

Backtracking

Find First and Last Position of Element in Sorted Array: Given an array of integers nums sorted in non-decreasing order, find the starting and ending position of a given target value.

Binary Search

Find Minimum in Rotated Sorted Array: Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. Find the minimum element.

Binary Search

Search in Rotated Sorted Array: You are given an integer array nums sorted in ascending order (with distinct values), and an integer target. Suppose that nums is rotated at some pivot unknown to you beforehand (0 <= i < nums.length). Return the index of target if it is in nums, or -1 if it is not in nums.

Binary Search

Kth Smallest Element in a BST: Given a binary search tree, find the kth smallest element in it.

Binary Search Tree

Median of Two Sorted Arrays: There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays.

Binary Search, Divide and Conquer

Number of 1 Bits: Write a function that takes an unsigned integer and returns the number of '1' bits it has (also known as the Hamming weight).

Bit Manipulation

Reverse Bits: Reverse bits of a given 32 bits unsigned integer.

Bit Manipulation

Sum of Two Integers: Calculate the sum of two integers a and b, but you are not allowed to use the operator + and -.

Bit Manipulation

Counting Bits: Given a non-negative integer num, for every number i in the range 0 ≤ i ≤ num, calculate the number of 1's in their binary representation and return them as an array.

Bit Manipulation, Dynamic Programming

Missing Number: Given an array containing n distinct numbers taken from 0, 1, 2, ..., n, find the one that is missing from the array.

Bit Manipulation, Math

Word Ladder: Given two words beginWord and endWord, and a dictionary wordList, return the length of the shortest transformation sequence from beginWord to endWord, such that: Only one letter can be changed at a time. Each transformed word must exist in the wordList. Return 0 if there is no such transformation sequence.

Breadth-First Search (BFS)

Binary Tree Level Order Traversal: Given a binary tree, return the level order traversal of its nodes' values.

Breadth-First Search (BFS), Tree

Binary Tree Zigzag Level Order Traversal: Given a binary tree, return the zigzag level order traversal of its nodes' values.

Breadth-First Search (BFS), Tree

Word Search: Given an m x n grid of characters board and a string word, return true if word exists in the grid. The word can be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once.

Depth-First Search (DFS), Backtracking

Pacific Atlantic Water Flow: Given an m x n matrix of non-negative integers representing the height of each unit cell in a continent, the "Pacific ocean" touches the left and top edges of the matrix and the "Atlantic ocean" touches the right and bottom edges. Water can only flow in four directions (up, down, left, or right) from a cell to another cell with height equal or lower. Return a list of grid coordinates where water can flow to both the Pacific and Atlantic oceans.

Depth-First Search (DFS), Breadth-First Search (BFS)

Number of Islands: Given an m x n 2D binary grid which represents a map of '1's (land) and '0's (water), return the number of islands.

Depth-First Search (DFS), Breadth-First Search (BFS), Union Find

Longest Increasing Path in a Matrix: Given an m x n integers matrix, return the length of the longest increasing path in matrix.

Depth-First Search (DFS), Topological Sort, Memoization

Binary Tree Maximum Path Sum: Given a binary tree, find the maximum path sum. The path may start and end at any node in the tree.

Depth-First Search (DFS), Tree

Word Search II: Given an m x n board of characters and a list of words, return all words in the board. Each word must be constructed from letters of sequentially adjacent cells, where adjacent cells are horizontally or vertically neighboring. The same letter cell may not be used more than once in a word.

Depth-First Search (DFS), Trie

Number of Provinces: There are n cities. Some of them are connected, while some are not. If city a is connected directly with city b, and city b is connected directly with city c, then city a is connected indirectly with city c. Return the total number of connected cities.

Depth-First Search (DFS), Union Find

Sliding Window Maximum: You are given an array of integers nums, there is a sliding window of size k which is moving from the very left of the array to the very right. You can only see the k numbers in the window. Each time the sliding window moves right by one position. Return the max sliding window.

Deque (Double-ended Queue), Sliding Window

Design Tic-Tac-Toe: Design a Tic-Tac-Toe game that is played between two players on a n x n grid. You may assume the following rules: A move is guaranteed to be valid and is placed on an empty block. Once a winning condition is reached, no more moves are allowed. A player who succeeds in placing n of their marks in a horizontal, vertical, or diagonal row wins the game.

Design

Encode and Decode Strings (Leetcode Premium): Design an algorithm to encode a list of strings to a string. The encoded string is then sent over the network and is decoded back to the original list of strings.

Design

LRU Cache: Design and implement a data structure for Least Recently Used (LRU) cache. It should support the following operations: get and put.

Design, Doubly Linked List

Insert Delete GetRandom O(1): Design a data structure that supports all following operations in average O(1) time. insert(val) - Inserts an item val to the set if not already present. remove(val) - Removes an item val from the set if present. getRandom() - Returns a random element from the current set of elements.

Design, Hash Table

Logger Rate Limiter: Design a logger system that receives a stream of messages along with their timestamps. Return true if the message should be printed in the given timestamp, otherwise return false.

Design, Hash Table

Find Median from Data Stream: Design a data structure that supports the following two operations: void addNum(int num) - Add a integer number from the data stream to the data structure. double findMedian() - Return the median of all elements so far.

Design, Heap

Moving Average from Data Stream: Design a class MovingAverage that supports the following operations: MovingAverage(int size) Initializes the object with the size of the window. double next(int val) Returns the moving average of the last size values of the stream.

Design, Queue

Max Stack: Design a max stack that supports push, pop, top, peekMax, and popMax.

Design, Stack

Min Stack: Design a stack that supports push, pop, top, getMin and retrieving the minimum element in constant time.

Design, Stack

Add and Search Word: Design a data structure that supports adding new words and searching for words with a wildcard pattern.

Design, Trie

Implement Trie (Prefix Tree): Implement a trie with insert, search, and startsWith methods.

Design, Trie

Climbing Stairs: You are climbing a staircase. It takes n steps to reach the top. Each time you can either climb 1 or 2 steps. In how many distinct ways can you climb to the top?

Dynamic Programming

Coin Change: You are given an integer array coins representing coins of different denominations and an integer amount representing a total amount of money. Return the fewest number of coins that you need to make up that amount.

Dynamic Programming

Decode Ways: A message containing letters from A-Z can be encoded into numbers using the following mapping: 'A' -> 1, 'B' -> 2, ..., 'Z' -> 26. Given a string s containing only digits, return the number of ways to decode it.

Dynamic Programming

House Robber II: You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. The only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night. Return the maximum amount of money you can rob without alerting the police.

Dynamic Programming

House Robber: You are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed. The only constraint stopping you from robbing each of them is that adjacent houses have security systems connected and it will automatically contact the police if two adjacent houses were broken into on the same night. Return the maximum amount of money you can rob without alerting the police.

Dynamic Programming

Longest Common Subsequence: Given two strings text1 and text2, return the length of their longest common subsequence.

Dynamic Programming

Longest Increasing Subsequence: Given an integer array nums, return the length of the longest strictly increasing subsequence.

Dynamic Programming

Maximum Product Subarray: Given an integer array nums, find the contiguous subarray within an array (containing at least one number) which has the largest product.

Dynamic Programming

Palindromic Substrings: Given a string, your task is to count how many palindromic substrings in this string.

Dynamic Programming

Race Car: Your car starts at position 0 and speed +1 on an infinite number line. (Your car can go into negative positions.) Your target is to drive to the target position.

Dynamic Programming

Regular Expression Matching: Given an input string (s) and a pattern (p), implement regular expression matching with support for '.' and '*'.

Dynamic Programming

Unique Paths: A robot is located at the top-left corner of a m x n grid. The robot can only move either down or right at any point in time. How many possible unique paths are there?

Dynamic Programming

Word Break Problem: Given a non-empty string s and a dictionary wordDict containing a list of non-empty words, determine if s can be segmented into a space-separated sequence of one or more dictionary words.

Dynamic Programming

Best Time to Buy and Sell Stock: Say you have an array for which the ith element is the price of a given stock on day i. Design an algorithm to find the maximum profit.

Dynamic Programming, Array

Maximum Subarray: Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.

Dynamic Programming, Divide and Conquer

Longest Valid Parentheses: Given a string containing just the characters '(' and ')', find the length of the longest valid (well-formed) parentheses substring.

Dynamic Programming, Stack

Longest Palindromic Substring: Given a string s, find the longest palindromic substring in s.

Dynamic Programming, String

Clone Graph: Given a reference of a node in a connected undirected graph, return a deep copy (clone) of the graph.

Graph, Depth-First Search (DFS), Breadth-First Search (BFS)

Jump Game II: Given an array of non-negative integers nums, you are initially positioned at the first index. Each element in the array represents your maximum jump length from that position. Your goal is to reach the last index in the minimum number of jumps.

Greedy, Array

Jump Game: Given an array of non-negative integers nums, you are initially positioned at the first index. Each element in the array represents your maximum jump length from that position. Determine if you can reach the last index.

Greedy, Array

Non-overlapping Intervals: Given a collection of intervals, find the minimum number of intervals you need to remove to make the rest of the intervals non-overlapping.

Greedy, Sorting

Contains Duplicate II: Given an array of integers and an integer k, find out whether there are two distinct indices i and j in the array such that nums[i] = nums[j] and the absolute difference between i and j is at most k.

Hash Table

Valid Sudoku: Determine if a 9x9 Sudoku board is valid.

Hash Table

Verifying an Alien Dictionary: In an alien language, surprisingly, they also use English lowercase letters, but possibly in a different order. The order of the alphabet is some permutation of lowercase letters. Given a sequence of words written in the alien language, and the order of the alphabet, return true if and only if the given words are sorted lexicographically in this alien language.

Hash Table

Contains Duplicate: Given an array of integers, find if the array contains any duplicates.

Hash Table, Array

Majority Element: Given an array of size n, find the majority element. The majority element is the element that appears more than ⌊n / 2⌋ times.

Hash Table, Divide and Conquer

Top K Frequent Elements: Given an integer array nums and an integer k, return the k most frequent elements.

Hash Table, Heap

Longest Substring Without Repeating Characters: Given a string s, find the length of the longest substring without repeating characters.

Hash Table, Two Pointers, String

Longest Consecutive Sequence: Given an unsorted array of integers nums, return the length of the longest consecutive elements sequence.

Hash Table, Union Find

High Five: Given a list of scores of different students, return the average score of each student's top five scores in the order of each student's id.

Heap

Kth Largest Element in an Array: Find the kth largest element in an unsorted array.

Heap, Divide and Conquer

Employee Free Time: We are given a list schedule of employees, which represents the working time for each employee. Each employee has a list of non-overlapping Intervals, and these intervals are in sorted order. Return the list of finite intervals representing common, positive-length free time for all employees, also in sorted order.

Heap, Greedy

Merge Two Sorted Lists: Merge two sorted linked lists and return it as a sorted list.

Linked List

Middle of the Linked-List: Given a non-empty, singly linked list with a head node head, return a middle node of linked list.

Linked List

Reorder List: Given a singly linked list L: L0 → L1 → ... → Ln-1 → Ln, reorder it to: L0 → Ln → L1 → Ln-1 → L2 → Ln-2 → ... You may not modify the values in the list's nodes, only nodes itself may be changed.

Linked List

Reverse Nodes in k-Group: Given a linked list, reverse the nodes of a linked list k at a time and return its modified list. k is a positive integer and is less than or equal to the length of the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should remain as it is.

Linked List

Reverse a Linked List: Reverse a singly linked list.

Linked List

Copy List with Random Pointer: A linked list of length n is given such that each node contains an additional random pointer, which could point to any node in the list or null. Return a deep copy of the list.

Linked List, Hash Table

Add Two Numbers: You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.

Linked List, Math carry = sum / 10; // Integer division. I.e. Math.floor() behavior result = sum % 10;

Sort List: Given the head of a linked list, return the list after sorting it in ascending order.

Linked List, Sorting

Detect Cycle in a Linked List: Given a linked list, return the node where the cycle begins. If there is no cycle, return null.

Linked List, Two Pointers

Palindrome Linked List: Given a singly linked list, determine if it is a palindrome.

Linked List, Two Pointers

Fizz Buzz: Write a program that outputs the string representation of numbers from 1 to n. But for multiples of three, it should output "Fizz" instead of the number, and for the multiples of five, it should output "Buzz". For numbers which are multiples of both three and five, output "FizzBuzz".

Math

Roman to Integer: Given a roman numeral, convert it to an integer.

Math, String

Minimum Window Substring: Given two strings s and t, return the minimum window in s which will contain all the characters in t.

Sliding Window

Largest Number: Given a list of non-negative integers nums, arrange them such that they form the largest number.

Sorting

Remove Interval: Given a sorted list of disjoint intervals, each interval intervals[i] is an interval representing the ith demand. A disjoint interval interval is an interval [a, b], for which there are no integers x and y such that x < y < a or x > y > b.

Sorting

Sort Colors: Given an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.

Sorting

Merge Intervals: Given a collection of intervals, merge all overlapping intervals.

Sorting, Array

Meeting Rooms (Leetcode Premium): Given an array of meeting time intervals where intervals[i] = [starti, endi], determine if a person could attend all meetings.

Sorting, Greedy

Valid Anagram: Given two strings s and t, write a function to determine if t is an anagram of s.

Sorting, Hash Table

Group Anagrams: Given an array of strings, group anagrams together.

Sorting, Hash Table, String

Meeting Rooms II (Leetcode Premium): Given an array of meeting time intervals intervals where intervals[i] = [starti, endi], return the minimum number of conference rooms required.

Sorting, Heap, Greedy

Merge K Sorted Lists: Merge k sorted linked lists and return it as one sorted list.

Sorting, Heap, Linked List

Largest Rectangle in Histogram: Given n non-negative integers representing the histogram's bar height where the width of each bar is 1, find the area of the largest rectangle in the histogram.

Stack

Minimum Remove to Make Valid Parentheses: Given a string s of '(' , ')' and lowercase English characters. Your task is to remove the minimum number of parentheses ( '(' or ')', in any positions ) so that the resulting parentheses string is valid and return any valid string.

Stack, String

Valid Parentheses: Given a string containing just the characters '(', ')', '{', '}', '[' and ']', determine if the input string is valid.

Stack, String

Longest Common Prefix: Write a function to find the longest common prefix string amongst an array of strings.

String

Text Justification: Given an array of words and a width maxWidth, format the text such that each line has exactly maxWidth characters and is fully (left and right) justified.

String

Alien Dictionary: There is a new alien language that uses the English alphabet. You are given a list of words from the dictionary where words are sorted lexicographically by the rules of this new language. Determine the order of characters in this language.

Topological Sort

Course Schedule II: There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1. Some courses may have prerequisites, and for each course, you are given a list of prerequisites courses[i]. Return the ordering of courses you should take to finish all courses.

Topological Sort, Graph

Course Schedule: There are a total of numCourses courses you have to take, labeled from 0 to numCourses-1. Some courses may have prerequisites, and for each course, you are given a list of prerequisites courses[i]. Return true if you can finish all courses.

Topological Sort, Graph

Construct Binary Tree from Preorder and Inorder Traversal: Given two integer arrays preorder and inorder where preorder is the preorder traversal of a binary tree, and inorder is the inorder traversal of the same tree, construct and return the binary tree.

Tree

Find Leaves of Binary Tree: Given a binary tree, collect a tree's nodes as if you were doing this: Collect and remove all leaves, repeat until the tree is empty.

Tree

Flatten Binary Tree to Linked List: Given a binary tree, flatten it to a linked list in-place.

Tree

Lowest Common Ancestor of BST: Given a binary search tree (BST), find the lowest common ancestor (LCA) of two given nodes in the BST.

Tree

Same Tree: Given two binary trees, write a function to check if they are the same or not. Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

Tree

Serialize and Deserialize Binary Tree: Design an algorithm to serialize and deserialize a binary tree.

Tree

Symmetric Tree: Given a binary tree, check whether it is a mirror of itself (i.e., symmetric around its center).

Tree

Invert/Flip Binary Tree: Invert a binary tree.

Tree, Depth-First Search (DFS)

Maximum Depth of Binary Tree: Given a binary tree, find its maximum depth.

Tree, Depth-First Search (DFS)

Subtree of Another Tree: Given two non-empty binary trees s and t, check whether tree t has exactly the same structure and node values with a subtree of s. A subtree of s is a tree consists of a node in s and all of this node's descendants.

Tree, Depth-First Search (DFS)

Validate Binary Search Tree: Given the root of a binary tree, determine if it is a valid binary search tree (BST).

Tree, Depth-First Search (DFS), In-order Traversal

Container With Most Water: Given n non-negative integers a1, a2, ..., an where each represents a point at coordinate (i, ai). n vertical lines are drawn, and you are going to find two lines which together with the x-axis forms a container that contains the most water.

Two Pointers

Remove Duplicates from Sorted Array: Given a sorted array nums, remove the duplicates in-place such that each element appears only once and returns the new length.

Two Pointers, Array

Two Sum - II: Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

Two Pointers, Array

Remove Nth Node From End Of List: Given a linked list, remove the n-th node from the end of list and return its head.

Two Pointers, Linked List

Longest Repeating Character Replacement: Given a string s that consists of only uppercase English letters, you can perform at most k operations on that string. In one operation, you can choose any character of the string and change it to any other uppercase English character. Find the length of the longest subarray containing only repeating letters you can get after performing the above operations.

Two Pointers, Sliding Window

Trapping Rain Water: Given n non-negative integers representing an elevation map where the width of each bar is 1, compute how much water it can trap after raining.

Two Pointers, Stack

Valid Palindrome: Given a string, determine if it is a palindrome, considering only alphanumeric characters and ignoring cases.

Two Pointers, String

Graph Valid Tree (Leetcode Premium): Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to check whether these edges make up a valid tree.

Union Find, Graph

Number of Connected Components in an Undirected Graph (Leetcode Premium): Given n nodes labeled from 0 to n - 1 and a list of undirected edges (each edge is a pair of nodes), write a function to find the number of connected components in an undirected graph.

Union Find, Graph


Related study sets

Chapter 10: Promoting a Healthy Pregnancy, Unit 6, 10, & 16 - Care of Family Ch. 4, Care of Family Ch. 2, 3

View Set

Texas Gov: Chap 6-11 quizlet and quiz

View Set

CON 2370 Simplified Acquisition Procedures Take 14

View Set

Chapter 13 mastering biology assignment

View Set