Detailed Neetcode 150

0.0(0)
studied byStudied by 0 people
full-widthCall with Kai
GameKnowt Play
learnLearn
examPractice Test
spaced repetitionSpaced Repetition
heart puzzleMatch
flashcardsFlashcards
Card Sorting

1/149

encourage image

There's no tags or description

Looks like no tags are added yet.

Study Analytics
Name
Mastery
Learn
Test
Matching
Spaced

No study sessions yet.

150 Terms

1
New cards

Given a list of integers, return true if any value appears at least twice, else false.

Iterate through nums, adding each value to a set; if you ever see a value that's already in the set, return True - otherwise False after the loop. O(n) time, O(n) space.

2
New cards

Given two strings s and t, determine whether t is an anagram of s.

Count each character with an array or dict while iterating over both strings; they're anagrams iff all counts net to zero. O(n) time, O(1) extra space if using fixed‑size array.

3
New cards

Given an array of integers nums and an integer target, return indices of the two numbers that add up to target.

Keep a hash map from value→index; for each num x at index i, check if target‑x is already in the map. Insert x afterward. O(n) time, O(n) space.

4
New cards

Given an array of strings, group the strings that are anagrams of each other.

For every word build a canonical key (sorted letters or 26‑char frequency tuple) and append the word to a hash‑map bucket keyed by that signature. O(n·k log k) with sorting, O(n·k) with tuple key.

5
New cards

Given an integer array nums and an integer k, return the k most frequent elements.

Count frequencies with a dict, then either bucket‑sort by frequency or push (−freq,val) into a min‑heap of size k. Both run in O(n) time on average.

6
New cards

Given an integer array nums, return an array answer where answer[i] is the product of all elements of nums except nums[i] (without using division).

Build prefix products left→right and suffix products right→left in two passes; result[i]=prefix[i‑1]*suffix[i+1]. O(n) time, O(1) extra space beyond output.

7
New cards

Given a 9×9 Sudoku board, determine if it is a valid Sudoku configuration.

Use three sets of 9 boolean arrays (rows, cols, 3×3 boxes); while scanning each cell ensure the digit hasn't appeared before in its row, col, or box. O(81) time, O(1) space.

8
New cards

Design encode and decode functions to convert a list of strings into a single string and back, guaranteeing lossless round‑trip.

To encode list[str], write len(s)+'#'+s for each string; to decode, read length up to '#', slice that many chars. Handles any UTF‑8 chars and '#'.

9
New cards

Given an unsorted array of integers, return the length of the longest consecutive elements sequence.

Insert all nums into a set; for each num that has no predecessor (num‑1 not in set) walk forward counting length until num+k not in set, tracking max. O(n) time/O(n) space.

10
New cards

Given a string s, return true if, after ignoring non‑alphanumeric chars and case, it reads the same forwards and backwards.

Two pointers from both ends skipping non‑alphanumerics; compare lowercase chars until they cross. O(n)/O(1).

11
New cards

Given a sorted integer array nums and an integer target, return the indices (1‑indexed) of the two numbers that add up to target.

Two pointers (lo,hi) traverse sorted array adjusting toward target; O(n) time, O(1) space.

12
New cards

Given an integer array nums, return all unique triplets [a,b,c] such that a + b + c = 0.

Sort nums; fix index i and run two‑pointer search on the rest to find complements of −nums[i], skipping duplicates. O(n²).

13
New cards

Given n lines of heights, find two lines that together with the x‑axis form a container containing the most water.

Two pointers at ends; compute area and move pointer at shorter wall inward to seek larger area. O(n).

14
New cards

Given elevation map heights where width = 1, compute how much water it can trap after raining.

Two‑pointer scan keeping leftMax/rightMax; at each step add trapped = max(0,min(lMax,rMax)-height[i]). O(n).

15
New cards

Given an array of stock prices, find the maximum profit from one buy-sell transaction.

Track min price so far and current profit = price - minPrice; update maxProfit each day. O(n).

16
New cards

Given a string s, find the length of the longest substring without repeating characters.

Sliding window with dict char→latest index; shrink window when duplicate seen; track max length. O(n).

17
New cards

Given a string s and an integer k, return the length of the longest substring you can obtain after replacing at most k characters so that the substring contains only one repeating letter.

Window counts plus maxFreq; shrink while window‑maxFreq>k; record longest. O(n).

18
New cards

Given two strings s1 and s2, return true if s2 contains a permutation of s1.

Sliding window length |p| with char frequency arrays; window matches pattern when counts equal. O(n).

19
New cards

Given strings s and t, return the minimal window in s that will contain all characters in t (including multiplicity).

Expand window until it contains all chars of t, then shrink from left while maintaining requirement; keep shortest window. O(n).

20
New cards

Given an array nums and a window size k, return the maximum value in each sliding window.

Monotonic deque of indices with decreasing values; front is maximum of current window. O(n).

21
New cards

Given a string containing brackets '()[]{}', determine if the string is valid.

Stack of opening brackets; pop and check type on closing bracket; valid if stack empty at end. O(n).

22
New cards

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

Maintain auxiliary stack of current mins paralleling push/pop operations; min is top of aux stack. O(1).

23
New cards

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Stack operands; on operator pop two, apply, push result; final element is answer. O(n).

24
New cards

Given n pairs of parentheses, return all combinations of well‑formed parentheses.

Backtrack keeping counts of open/close used; append to result when open==close==n.

25
New cards

Given an array of daily temperatures, return how many days you would have to wait until a warmer temperature for each day.

Monotonic stack of indices; for each day, pop while temp higher and compute wait; push index. O(n).

26
New cards

Given target distance and starting positions and speeds of cars driving toward it, count the number of car fleets that will arrive.

Sort cars by position descending, compute time = (target‑pos)/speed; count fleet when time > lastTime seen. O(n log n) sort + O(n).

27
New cards

Given histogram bar heights, return the area of the largest rectangle in the histogram.

Scan bars with increasing stack; compute area when current bar lower than stack top, using popped height and width. O(n).

28
New cards

Given a sorted array nums and a target, return the index of target if found, else ‑1.

Iteratively halve search range on sorted array until target found or bounds cross. O(log n).

29
New cards

Given an m×n matrix where each row is sorted and first element of each row is greater than last of previous row, search target.

Binary search treating matrix as flattened sorted list; map mid back to row/col. O(log mn).

30
New cards

Given piles of bananas and integer h, return the minimum integer speed k to eat all bananas within h hours.

Binary search speed 1..maxPile; total hours=Σ⌈pile/speed⌉; pick smallest speed meeting H. O(n log maxPile).

31
New cards

Given a rotated sorted array nums and a target, return the index of target or ‑1.

Binary search while checking which half is sorted to discard wrong half. O(log n).

32
New cards

Given a rotated sorted array nums, return the minimum element.

Binary search for pivot where array values decrease; min is at pivot. O(log n).

33
New cards

Design a time‑based key‑value store that supports set(key, value, timestamp) and get(key, timestamp) returning the value set for key at the largest timestamp ≤ query time.

Dict key→list[(ts,val)]; set appends; get uses bisect to find latest ts ≤ query. O(log m).

34
New cards

Given two sorted arrays nums1 and nums2, return their median in O(log(m+n)) time.

Binary search partition of shorter array such that left parts size equal and maxLeft ≤ minRight; derive median. O(log min(m,n)).

35
New cards

Given head of a singly linked list, reverse the list and return the new head.

Iterative pointer reversal with prev, cur, next; return prev at end. O(n).

36
New cards

Merge two sorted linked lists into a single sorted list and return it.

Iteratively build new list taking smaller head from l1 or l2 each step. O(m+n).

37
New cards

Given head of linked list, reorder it to: L0→Ln→L1→Ln-1→... in place.

1) find mid, 2) reverse second half, 3) merge nodes alternately from start and reversed half.

38
New cards

Remove the n‑th node from the end of a linked list and return its head.

Advance fast n nodes then move slow & fast until fast.next=None; delete slow.next.

39
New cards

Deep‑copy a linked list where each node has next and random pointers.

Clone nodes interleaved, set random via original.random.next, then separate lists. O(n)/O(1).

40
New cards

Add two non‑negative integers represented by reversed linked lists and return the sum as a linked list.

Traverse both lists adding digits and carry; create new nodes; after loop add carry if any. O(max(m,n)).

41
New cards

Given head of a linked list, determine if the linked list has a cycle.

Floyd's tortoise and hare: fast moves 2, slow moves 1; meet implies cycle.

42
New cards

Given array nums containing n+1 integers where each integer is between 1 and n inclusive, return the duplicate number.

Floyd's cycle detection on index graph nums[i]; entrance is duplicate.

43
New cards

Design a least‑recently‑used (LRU) cache that supports get and put in O(1) time.

Hash map key→node plus doubly‑linked list; on access move node to head; on insert evict tail when size exceeds cap.

44
New cards

Merge k sorted linked lists and return one sorted list.

Min‑heap of current heads; pop min, push its next; build merged list. O(N log k).

45
New cards

Reverse nodes of a linked list in groups of size k and return modified list.

Iteratively reverse sublists of length k using pointer manipulation; leave remainder

46
New cards

Invert (mirror) a binary tree.

Recursively swap left/right child of each node.

47
New cards

Given a binary tree, return its maximum depth (root to deepest leaf length).

Post‑order DFS returning 1+max(leftDepth,rightDepth).

48
New cards

Given a binary tree, return the length (number of edges) of the diameter of the tree.

DFS returning height; update global best with left+right heights each node.

49
New cards

Given a binary tree, determine if it is height‑balanced.

DFS returning height if balanced else ‑1 early exit.

50
New cards

Given two binary trees, determine if they are the same tree.

DFS comparing val, left subtree, right subtree for equality.

51
New cards

Given root and subRoot of two binary trees, return true if subRoot is a subtree of root.

DFS through main tree calling isSame at each node until match found.

52
New cards

Given a binary search tree (BST) and two nodes, return their lowest common ancestor.

Iterate from root; move to child side where both p and q lie until diverge.

53
New cards

Return the level‑order traversal of a binary tree's node values.

Queue BFS collecting node values by level.

54
New cards

Return the list of node values visible from the right side of a binary tree.

BFS saving last node per level or DFS right‑first capturing first visit depth.

55
New cards

Return number of good nodes in binary tree where good node is >= all previous on root‑to‑node path.

DFS passing pathMax; node is good if val≥pathMax; recurse updating max.

56
New cards

Determine if a binary tree is a valid binary search tree (BST).

In‑order traversal ensuring current val > previous val.

57
New cards

Given a BST and integer k, return the k‑th smallest element.

In‑order traversal decrement k until zero then return node value.

58
New cards

Construct binary tree from preorder and inorder traversal arrays.

Use preorder index to pick root; split inorder into left/right; recurse; store inorder value→index for O(1) splits.

59
New cards

Return the maximum path sum in a non‑empty binary tree (sum of node values).

DFS returns max downward path; update global with left+right+node.

60
New cards

Design algorithms to serialize and deserialize a binary tree.

Preorder serialization with '#' for nulls; deserialize by reading tokens recursively.

61
New cards

Implement a trie with insert, search, and startsWith methods.

Each node stores children dict and end flag; insert/search/prefix all straightforward.

62
New cards

Design a data structure that adds words and can search a word with '.' wildcard matching any letter.

Trie search supports '.' wildcard by DFS exploring all children when char=='.'.

63
New cards

Given a board of letters and a list of words, return all words on the board.

Insert words into trie; DFS backtracking on board pruning dead paths; mark found words to avoid duplicates.

64
New cards

Design a class that on add(val) and kthLargest() returns the k‑th largest element in the stream.

Keep min‑heap of size k; push val, pop when size>k; kth largest is heap[0].

65
New cards

Smash rocks: each turn take two heaviest stones and smash; return weight of last stone (or 0).

Max‑heap stones; repeatedly smash top two; push diff if non‑zero; return remaining or 0.

66
New cards

Given points on 2D plane and integer k, return k points closest to origin.

Max‑heap size k storing (dist,point); push and pop if size>k; return stored points.

67
New cards

Find the kth largest element in an unsorted array.

Quickselect partition average O(n) or min‑heap size k for O(n log k).

68
New cards

Given tasks represented by letters and an integer n cooling interval, return least total units of time needed to finish all tasks.

Greedy formula: idleSlots=(maxFreq‑1)*(n+1‑r) minus tasks counts; answer=max(len(tasks),len(tasks)+idleSlots).

69
New cards

Design a simplified Twitter with posting, following, unfollowing, and news feed of recent tweets.

Hash maps for follow relationships and per‑user tweet list; news feed merges recent tweets with max‑heap of (time,tweetId).

70
New cards

Maintain a data stream so that addNum and findMedian operate efficiently.

Two heaps - max‑heap lower half, min‑heap upper; rebalance sizes; median is avg of roots or root of bigger heap.

71
New cards

Given a set of unique integers, return all possible subsets (the power set).

Backtracking building path or bitmask enumeration for all 2^n subsets.

72
New cards

Given candidates with unlimited reuse, return all unique combinations summing to target.

DFS choosing candidate >= current index, passing remaining target; backtrack when remainder negative.

73
New cards

Given a list of unique integers, return all possible permutations.

Backtrack swapping current index with each idx≥current; restore order on return.

74
New cards

Given a list that may contain duplicates, return all possible distinct subsets.

Sort nums; backtrack skipping duplicates when choosing next element.

75
New cards

Given candidates can be used at most once, return unique combinations summing to target.

Sort nums; backtrack, at each depth skip duplicates; each element used at most once.

76
New cards

Given a board and a word, determine if word exists in grid via adjacent letters (no reuse).

DFS backtracking on grid matching word letters with visited set; prune on mismatch.

77
New cards

Partition a string into all possible lists of palindromic substrings.

Backtrack choosing palindrome prefixes; recurse on suffix; gather partitions.

78
New cards

Given digits as a string, return all possible letter combinations using telephone keypad mapping.

Backtracking appending letters for each digit until length==digits length.

79
New cards

Return all distinct solutions to the n‑queens puzzle.

Backtrack rows using sets for cols and diagonals; construct board on success.

80
New cards

Given a grid of '1's and '0's, return the number of islands.

DFS/BFS marking visited land cells to count connected components.

81
New cards

Clone an undirected graph and return the cloned graph's reference node.

DFS/BFS cloning nodes with hashmap mapping original→clone.

82
New cards

Given grid of land and water, return area of largest island.

DFS flood fill counting area; track maximum.

83
New cards

Given heights matrix, return cells that can flow water to both Pacific and Atlantic oceans.

BFS/DFS from Pacific and Atlantic edges separately; cells reachable by both in intersection.

84
New cards

Capture all regions surrounded by 'X' on a board by flipping surrounded 'O's to 'X'.

DFS from border 'O's marking safe; flip remaining 'O's to 'X'.

85
New cards

Given grid of fresh and rotten oranges, return minutes until all oranges are rotten, or ‑1.

Multi‑source BFS from initial rotten cells; minutes equals levels; return -1 if fresh remains.

86
New cards

Given grid with walls, gates, and empty rooms, fill each empty room with distance to nearest gate.

Multi‑source BFS from gate cells, writing steps to each empty room.

87
New cards

Given number of courses and prerequisite pairs, determine if it is possible to finish all courses.

Topological sort via indegree queue; detect cycle by processed count.

88
New cards

Return an order of courses to finish all given prerequisites or empty array if impossible.

Same as above but append nodes to ordering vector as they're processed.

89
New cards

Given edges that form a tree with one extra edge, return the edge that can be removed to make tree.

Union‑Find; first edge connecting vertices already in same set is redundant.

90
New cards

Given n nodes and undirected edges, return number of connected components.

Union‑Find merging edges; initially n sets; answer is number of roots.

91
New cards

Determine if given edges form a valid tree of n nodes.

Graph with n nodes is tree if connected and edges==n‑1; use union‑find or DFS to test.

92
New cards

Return shortest transformation sequence length from beginWord to endWord, altering one letter at a time using dictionary words.

BFS using intermediate wildcard mapping for neighbor generation; return level when end reached.

93
New cards

Given flight tickets, reconstruct itinerary starting from 'JFK' and in lexical order.

Hierholzer's algorithm with min‑heap adjacency lists; postorder DFS and reverse result.

94
New cards

Given points in a plane, return minimum cost to connect all points by edges with Manhattan distance.

Prim's MST using min‑heap of (dist, node); pushed edges from current MST frontier.

95
New cards

Given times (u,v,w), number of nodes n, and source k, return time for all nodes to receive signal, else -1.

Dijkstra using adjacency list; answer is max distance if all nodes reachable else -1.

96
New cards

Grid heights; water rises over time; return minimum time required for swimmer to reach bottom‑right.

Dijkstra on grid where edge weight is max(currentHeight,nextHeight); min time to reach end.

97
New cards

Given sorted dictionary of alien language, return character ordering of the language.

Build precedence graph by comparing consecutive words; Kahn topological sort; detect cycle.

98
New cards

Given flights with prices, source, destination, and at most k stops, return cheapest price or ‑1.

Use BFS/Dijkstra with (node, stops) state, or Bellman‑Ford K+1 iterations; track min cost within K stops.

99
New cards

Given n, return number of distinct ways to climb to the top if at each step you can climb 1 or 2 stairs.

Fib DP with two variables updated iteratively.

100
New cards

Given cost array, return minimum cost to reach top climbing 1 or 2 steps starting at step 0 or 1.

DP from bottom: cost[i]+=min(cost[i+1],cost[i+2]); or forward DP.