Questions From Neetcode
Questions From Neetcode
You must implement an algorithm that runs in O(n) time and uses O(1) auxiliary space.
Brute Force
public class Solution {
public int firstMissingPositive(int[] nums) {
int missing = 1;
while (true) {
boolean flag = true;
for (int num : nums) {
if (missing == num) {
flag = false;
break;
}
}
if (flag) return missing;
missing++;
}
}
}
Negative Marking
public class Solution {
public int firstMissingPositive(int[] nums) {
int n = nums.length;
1
nums[i] = 0;
}
}
return n + 1;
}
}
Key Observations:
1. We're only interested in numbers from 1 to n (inclusive), where n is the length of the
array.
3. The idea is to put each number in its correct index position, i.e., number 1 at index 0,
2 at index 1, ..., n at index n-1.
// Step 2: Scan through the array to find the first number out
of place
for (int i = 0; i < n; i++) {
// If nums[i] != i + 1, then i + 1 is the missing number
if (nums[i] != i + 1)
return i + 1;
}
🧠 Example:
Input: [3, 4, -1, 1]
After rearranging: [1, -1, 3, 4]
Scan through:
3
● Index 0 → 1 ✅
● Index 1 → -1 ❌ → So answer is 2
Output: 2
📈 Complexity:
● Time: O(n) → Each number is moved at most once.
You are given two strings word1 and word2. Merge the strings by adding letters in alternating order,
starting with word1. If a string is longer than the other, append the additional letters onto the end of
the merged string.
Example 1:
Input: word1 = "abc", word2 = "pqr"
Output: "apbqcr"
Explanation: The merged string will be merged as so:
word1: a b c
word2: p q r
merged: a p b q c r
Example 2:
Input: word1 = "ab", word2 = "pqrs"
Output: "apbqrs"
Explanation: Notice that as word2 is longer, "rs" is appended to the end.
word1: a b
word2: p q r s
merged: a p b q r s
Example 3:
Input: word1 = "abcd", word2 = "pq"
Output: "apbqcd"
Explanation: Notice that as word1 is longer, "cd" is appended to the end.
word1: a b c d
word2: p q
merged: a p b q c d
4
Explanation
Two Pointers - I
public class Solution {
public String mergeAlternately(String word1, String word2) {
StringBuilder res = new StringBuilder();
int i = 0, j = 0;
while (i < word1.length() && j < word2.length()) {
res.append(word1.charAt(i++));
res.append(word2.charAt(j++));
}
res.append(word1.substring(i));
res.append(word2.substring(j));
return res.toString();
}
}
Time complexity: O(n + m), Space complexity: O(n + m), where n and m are the lengths of
word1 and word2.
One Pointer
5
11. Container With Most Water
You are given an integer array height of length n. There are n vertical lines drawn such that the two
endpoints of the ith line are (i, 0) and (i, height[i]).
Find two lines that together with the x-axis form a container, such that the container contains the
most water.
Example 1:
Output: 49
Explanation: The above vertical lines are represented by array [1,8,6,2,5,4,8,3,7]. In this case, the
max area of water (blue section) the container can contain is 49.
Example 2:
Output: 1
6
1. Brute Force
Two Pointers
public class Solution {
public int maxArea(int[] heights) {
int l = 0;
int r = heights.length - 1;
int res = 0;
while (l < r) {
int area = Math.min(heights[l], heights[r]) * (r - l);
res = Math.max(res, area);
if (heights[l] <= heights[r]) {
l++;
} else {
r--;
}
}
return res;
}
}
7
Boats to Save People -
Explanation
You are given an array people where people[i] is the weight of the ith person, and an infinite number
of boats where each boat can carry a maximum weight of limit. Each boat carries at most two
people at the same time, provided the sum of the weight of those people is at most limit.
Example 1:
Example 2:
Example 3:
8
Counting Sort
public class Solution {
public int numRescueBoats(int[] people, int limit) {
int m = Arrays.stream(people).max().getAsInt();
int[] count = new int[m + 1];
for (int p : people) {
count[p]++;
}
int idx = 0, i = 1;
while (idx < people.length) {
while (count[i] == 0) {
i++;
}
people[idx++] = i;
count[i]--;
}
Time complexity: O(n), Space complexity: O(m), where n is the size of the input array and m is
the maximum value in the array.
Contains Duplicate II -
Explanation
1. Brute Force
9
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
for (int L = 0; L < nums.length; L++) {
for (int R = L + 1; R < Math.min(nums.length, L + k + 1); R++) {
if (nums[L] == nums[R]) {
return true;
}
}
}
return false;
}
}
Hash Map
public class Solution {
public boolean containsNearbyDuplicate(int[] nums, int k) {
Map<Integer, Integer> map = new HashMap<>();
return false;
}
}
Time complexity: O(n), Space complexity: O(n), where n is the size of the array nums and k is the
maximum distance between two equal numbers.
Brute Force
10
public class Solution {
public int minSubArrayLen(int target, int[] nums) {
int n = nums.length;
int res = Integer.MAX_VALUE;
Sliding Window
public class Solution {
public int minSubArrayLen(int target, int[] nums) {
int l = 0, total = 0;
int res = Integer.MAX_VALUE;
11
Find K Closest Elements
Given a sorted integer array arr, two integers k and x, return the k closest integers to x in the array.
The result should also be sorted in ascending order.
● |a - x| < |b - x|, or
● |a - x| == |b - x| and a < b
●
Example 1:
Output: [1,2,3,4]
Example 2:
Output: [1,1,2,3]
list.sort((a, b) -> {
int diff = Math.abs(a - x) - Math.abs(b - x);
return diff == 0 ? Integer.compare(a, b) : diff;
});
12
Space complexity: O(1) or O(n) depending on the sorting algorithm, and O(k) for the
output array.
Two Pointers
public class Solution {
public List<Integer> findClosestElements(int[] arr, int k, int x) {
int l = 0, r = arr.length - 1;
while (r - l >= k) {
if (Math.abs(x - arr[l]) <= Math.abs(x - arr[r])) {
r--;
} else {
l++;
}
}
List<Integer> result = new ArrayList<>();
for (int i = l; i <= r; i++) {
result.add(arr[i]);
}
return result;
}
}
Time complexity: O(n − k), Space complexity: O(k) for the output array.
Binary Search
public class Solution {
public List<Integer> findClosestElements(int[] arr, int k, int x) {
int l = 0, r = arr.length - k;
while (l < r) {
int m = (l + r) / 2;
if (x - arr[m] > arr[m + k] - x) {
l = m + 1;
} else {
r = m;
}
}
List<Integer> result = new ArrayList<>();
for (int i = l; i < l + k; i++) {
result.add(arr[i]);
13
}
return result;
}
}
Time complexity: O(log(n − k) + k), Space complexity: O(k) for the output array,
where n is the size of the input array and k is the number of closest elements to find.
Example 1:
Example 2:
Sliding Window
14
int have = 0, need = countT.size();
int[] res = {-1, -1};
int resLen = Integer.MAX_VALUE;
int l = 0;
Time complexity: O(n), Space complexity: O(m), where n is the length of the string s
and m is the total number of unique characters in the strings t and s.
15
Time Based Key-Value Store
Design a time-based key-value data structure that can store multiple values for the same key at
different time stamps and retrieve the key's value at a certain timestamp.
Input
["TimeMap", "set", "get", "get", "set", "get", "get"]
[[], ["foo", "bar", 1], ["foo", 1], ["foo", 3], ["foo", "bar2", 4], ["foo", 4], ["foo", 5]]
Output
[null, null, "bar", "bar", null, "bar2", "bar2"]
public TimeMap() {
keyStore = new HashMap<>();
}
16
}
}
if (seen == 0) return "";
int back = keyStore.get(key).get(seen).size() - 1;
return keyStore.get(key).get(seen).get(back);
}
}
public TimeMap() {
m = new HashMap<>();
}
17
Find in Mountain Array
(This problem is an interactive problem.)
You may recall that an array arr is a mountain array if and only if:
● arr.length >= 3
● There exists some i with 0 < i < arr.length - 1 such that:
● arr[0] < arr[1] < ... < arr[i - 1] < arr[i]
● arr[i] > arr[i + 1] > ... > arr[arr.length - 1]
Given a mountain array mountainArr, return the minimum index such that mountainArr.get(index) ==
target. If such an index does not exist, return -1.
You cannot access the mountain array directly. You may only access the array using a
MountainArray interface:
Submissions making more than 100 calls to MountainArray.get will be judged Wrong Answer. Also,
any solutions that attempt to circumvent the judge will result in disqualification.
Example 1:
Brute Force
/**
* // This is MountainArray's API interface.
* // You should not implement it, or speculate about its implementation
* interface MountainArray {
18
* public int get(int index) {}
* public int length() {}
*}
*/
return -1;
}
}
Binary Search
/**
* // This is MountainArray's API interface.
* // You should not implement it, or speculate about its implementation
* interface MountainArray {
* public int get(int index) {}
* public int length() {}
*}
*/
// Find Peak
int l = 1, r = length - 2, peak = 0;
while (l <= r) {
int m = (l + r) / 2;
int left = mountainArr.get(m - 1);
int mid = mountainArr.get(m);
int right = mountainArr.get(m + 1);
if (left < mid && mid < right) {
l = m + 1;
19
} else if (left > mid && mid > right) {
r = m - 1;
} else {
peak = m;
break;
}
}
return -1;
}
}
20
Count Good Nodes in Binary Tree
Medium
Within a binary tree, a node x is considered good if the path from the root of the
tree to the node x contains no nodes with a value greater than the value of node
x
Given the root of a binary tree root, return the number of good nodes within the
tree.
Output: 3
21
Example 2:
Output: 4
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
22
* this.left = left;
* this.right = right;
* }
*}
*/
class Solution {
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
23
* this.left = left;
* this.right = right;
* }
*}
*/
while (!q.isEmpty()) {
Pair<TreeNode, Integer> pair = q.poll();
TreeNode node = pair.getKey();
int maxval = pair.getValue();
if (node.val >= maxval) {
res++;
}
if (node.left != null) {
q.offer(new Pair<>(node.left, Math.max(maxval, node.val)));
}
if (node.right != null) {
q.offer(new Pair<>(node.right, Math.max(maxval, node.val)));
}
}
return res;
}
}
Besides the root, each house has one and only one parent house. After a tour, the smart thief
realized that all houses in this place form a binary tree. It will automatically contact the police if two
directly-linked houses were broken into on the same night.
Given the root of the binary tree, return the maximum amount of money the thief can rob without
alerting the police.
24
Example 1:
Example 2:
25
1. Recursion
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
*}
*/
public class Solution {
public int rob(TreeNode root) {
if (root == null) {
return 0;
}
26
Dynamic Programming (Memoization)
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
*}
*/
public class Solution {
private Map<TreeNode, Integer> cache;
27
Time complexity: O(n)
Space complexity: O(n)
28
}
}
Time complexity: O(n)
Space complexity: O(n) for recursion stack.
Note that once you delete a leaf node with value target, if its parent node becomes a leaf node and
has the value target, it should also be deleted (you need to continue doing that until you cannot).
Example 1:
Example 2:
Example 3:
29
Input: root = [1,2,null,2,null,2], target = 2
Output: [1]
Explanation: Leaf nodes in green with value (target = 2) are removed at each step.
30
return null;
}
return root;
}
}
Time complexity: O(n)
Space complexity: O(n) for recursion stack.
We are playing a game with the stones. On each turn, we choose the heaviest two stones and
smash them together. Suppose the heaviest two stones have weights x and y with x <= y. The result
of this smash is:
Return the weight of the last remaining stone. If there are no stones left, return 0.
1. Sorting
public class Solution {
public int lastStoneWeight(int[] stones) {
List<Integer> stoneList = new ArrayList<>();
for (int stone : stones) {
stoneList.add(stone);
}
31
}
4o mini
Binary Search
public class Solution {
public int lastStoneWeight(int[] stones) {
Arrays.sort(stones);
int n = stones.length;
while (n > 1) {
int cur = stones[n - 1] - stones[n - 2];
n -= 2;
if (cur > 0) {
int l = 0, r = n;
while (l < r) {
int mid = (l + r) / 2;
if (stones[mid] < cur) {
l = mid + 1;
} else {
r = mid;
}
}
int pos = l;
n++;
stones = Arrays.copyOf(stones, n);
for (int i = n - 1; i > pos; i--) {
stones[i] = stones[i - 1];
}
stones[pos] = cur;
}
}
return n > 0 ? stones[0] : 0;
32
}
}
Heap
class Solution {
public int lastStoneWeight(int[] stones) {
PriorityQueue<Integer> minHeap = new PriorityQueue<>();
for (int s : stones) {
minHeap.offer(-s);
}
minHeap.offer(0);
return Math.abs(minHeap.peek());
}
}
The distance between two points on the X-Y plane is the Euclidean distance (i.e., √(x1 - x2)2 + (y1 -
y2)2).
33
You may return the answer in any order. The answer is guaranteed to be unique (except for the
order that it is in).
Example 2:
1. Sorting
34
public class Solution {
public int[][] kClosest(int[][] points, int k) {
Arrays.sort(points, (a, b) -> (a[0] * a[0] + a[1] * a[1]) -
(b[0] * b[0] + b[1] * b[1]));
return Arrays.copyOfRange(points, 0, k);
}
}
Min-Heap
public class Solution {
public int[][] kClosest(int[][] points, int K) {
PriorityQueue<int[]> minHeap = new PriorityQueue<>(Comparator.comparing(a -> a[0]));
for (int[] point : points) {
int dist = point[0] * point[0] + point[1] * point[1];
minHeap.offer(new int[]{dist, point[0], point[1]});
}
Task Scheduler
You are given an array of CPU tasks, each labeled with a letter from A to Z, and a number n. Each
CPU interval can be idle or allow the completion of one task. Tasks can be completed in any order,
but there's a constraint: there has to be a gap of at least n intervals between two tasks with the
same label.
Return the minimum number of CPU intervals required to complete all tasks.
35
Example 1:
Output: 8
Explanation: A possible sequence is: A -> B -> idle -> A -> B -> idle -> A -> B.
After completing task A, you must wait two intervals before doing A again. The same applies to
task B. In the 3rd interval, neither A nor B can be done, so you idle. By the 4th interval, you can
do A again as 2 intervals have passed.
Example 2:
Output: 6
With a cooling interval of 1, you can repeat a task after just one other task.
Example 3:
Output: 10
Explanation: A possible sequence is: A -> B -> idle -> idle -> A -> B -> idle -> idle -> A -> B.
There are only two types of tasks, A and B, which need to be separated by 3 intervals. This
leads to idling twice between repetitions of these tasks.
Brute Force
public class Solution {
public int leastInterval(char[] tasks, int n) {
int[] count = new int[26];
for (char task : tasks) {
count[task - 'A']++;
36
}
int time = 0;
List<Integer> processed = new ArrayList<>();
while (!arr.isEmpty()) {
int maxi = -1;
for (int i = 0; i < arr.size(); i++) {
boolean ok = true;
for (int j = Math.max(0, time - n); j < time; j++) {
if (j < processed.size() && processed.get(j) == arr.get(i)[1]) {
ok = false;
break;
}
}
if (!ok) continue;
if (maxi == -1 || arr.get(maxi)[0] < arr.get(i)[0]) {
maxi = i;
}
}
time++;
int cur = -1;
if (maxi != -1) {
cur = arr.get(maxi)[1];
arr.get(maxi)[0]--;
if (arr.get(maxi)[0] == 0) {
arr.remove(maxi);
}
}
processed.add(cur);
}
return time;
}
}
37
Max-Heap
public class Solution {
public int leastInterval(char[] tasks, int n) {
int[] count = new int[26];
for (char task : tasks) {
count[task - 'A']++;
}
int time = 0;
Queue<int[]> q = new LinkedList<>();
while (!maxHeap.isEmpty() || !q.isEmpty()) {
time++;
if (maxHeap.isEmpty()) {
time = q.peek()[1];
} else {
int cnt = maxHeap.poll() - 1;
if (cnt > 0) {
q.add(new int[]{cnt, time + n});
}
}
return time;
}
}
38
Greedy
public class Solution {
public int leastInterval(char[] tasks, int n) {
int[] count = new int[26];
for (char task : tasks) {
count[task - 'A']++;
}
Arrays.sort(count);
int maxf = count[25];
int idle = (maxf - 1) * n;
Given three integers a, b, and c, return the longest possible happy string. If there are multiple
longest happy strings, return any of them. If there is no such string, return the empty string "".
39
Example 1:
Input: a = 1, b = 1, c = 7
Output: "ccaccbcc"
Explanation: "ccbccacc" would also be a correct answer.
Example 2:
Input: a = 7, b = 1, c = 0
Output: "aabaa"
Explanation: It is the only correct answer in this case.
Greedy
public class Solution {
public String longestDiverseString(int a, int b, int c) {
int[] count = {a, b, c};
StringBuilder res = new StringBuilder();
40
if (res.length() > 1 && res.charAt(res.length() - 1)
== res.charAt(res.length() - 2)) {
repeated = maxChar;
} else {
repeated = -1;
}
}
return res.toString();
}
41
Time complexity: O(n)
Space complexity: O(1) extra space, O(n) for the output
string.
4o
Greedy (Max-Heap)
public class Solution {
public String longestDiverseString(int a, int b, int c) {
StringBuilder res = new StringBuilder();
PriorityQueue<int[]> maxHeap = new PriorityQueue<>((x, y) -> y[0] - x[0]);
while (!maxHeap.isEmpty()) {
int[] first = maxHeap.poll();
if (res.length() > 1 && res.charAt(res.length() - 1) == first[1] && res.charAt(res.length() -
2) == first[1]) {
if (maxHeap.isEmpty()) break;
int[] second = maxHeap.poll();
res.append((char) second[1]);
second[0]--;
if (second[0] > 0) maxHeap.offer(second);
maxHeap.offer(first);
} else {
res.append((char) first[1]);
first[0]--;
if (first[0] > 0) maxHeap.offer(first);
}
}
return res.toString();
}
}
42
Time complexity: O(n)
Space complexity: O(1) extra space, O(n) for the output string.
Car Pooling
There is a car with capacity empty seats. The vehicle only drives east (i.e., it cannot turn around and
drive west).
You are given the integer capacity and an array trips where trips[i] = [numPassengersi, fromi, toi]
indicates that the ith trip has numPassengersi passengers and the locations to pick them up and drop
them off are fromi and toi respectively. The locations are given as the number of kilometers due east
from the car's initial location.
Return true if it is possible to pick up and drop off all passengers for all the given trips, or false
otherwise.
Example 1:
Output: false
Example 2:
Output: true
Brute Force
43
public class Solution {
curPass += trips[j][0];
return false;
return true;
4o
44
Min-Heap
public class Solution {
int curPass = 0;
curPass -= minHeap.poll()[1];
curPass += numPass;
return false;
45
return true;
IPO
uppose LeetCode will start its IPO soon. In order to sell a good price of its shares to Venture Capital,
LeetCode would like to work on some projects to increase its capital before the IPO. Since it has
limited resources, it can only finish at most k distinct projects before the IPO. Help LeetCode design
the best way to maximize its total capital after finishing at most k distinct projects.
You are given n projects where the ith project has a pure profit profits[i] and a minimum capital of
capital[i] is needed to start it.
Initially, you have w capital. When you finish a project, you will obtain its pure profit and the profit will
be added to your total capital.
Pick a list of at most k distinct projects from given projects to maximize your final capital, and
return the final maximized capital.
46
for (int i = 0; i < capital.length; i++) {
minCapital.offer(i);
maxProfit.offer(minCapital.poll());
if (maxProfit.isEmpty()) {
break;
w += profits[maxProfit.poll()];
return w;
47
Example 1:
Example 2:
this.target = sum / k;
this.n = nums.length;
Arrays.sort(nums);
for (int i = 0; i < n / 2; i++) {
int tmp = nums[i];
nums[i] = nums[n - i - 1];
nums[n - i - 1] = tmp;
}
used = new boolean[n];
return backtrack(nums, k, 0, 0);
}
48
}
return false;
}
}
49