coding misc Flashcards
https://leetcode.com/problems/valid-parentheses/
don’t code; review logic
At closing bracket, must check if stack is empty
syntax for PQ that returns coordinate farthest from origin when you poll
PriorityQueue<int[]> maxPQ =
new PriorityQueue<>
(new Comparator<int[]>() {
public int compare(int[] left, int[] right) { return getEuclidDist(right) - getEuclidDist(left); }
});
https://leetcode.com/problems/design-twitter/description/
don’t code; review logic
follows map is { followerId : hash set of followees }
tweets map is ( userId : list of (timestamp, tweetId) )
use MAX pq, sorted by timestamp, when getting news feed
https://leetcode.com/problems/task-scheduler/
code and review logic
use map to get counts of each task, and put the counts in a max pq.
outer loop: while pq is not empty
inner: new cooldown queue each time; for loop for idle time. (add task to cooldown only if its count > 0)
https://leetcode.com/problems/single-threaded-cpu/
code and review logic
sort input array by enqueue time.
min heap, by processing time. each min heap item must also include the index.
start off time at the first enqueue time, and fast-forward instead of incrementing.
instead of while pq is not empty, it is while outputIdx < output.length. inner loop: tasks should be added to pq as long as time is valid.
syntax for converting a map of char counts into a pq
PriorityQueue<Character> pq = new PriorityQueue<>((a, b) ->
Integer.compare(counts.get(b), counts.get(a))); // max heap</Character>
pq.addAll(counts.keySet());
https://leetcode.com/problems/reorganize-string/description/
code and review logic
as i’m filling out the hash map of counts, if any count exceeds len/2, or (len + 1)/2 for odd len, immediately return “”.
very similar to processing tasks w/ cooldown, but instead of having a for loop counting cooldown time, i must write out the processing of 2 consecutive tasks b/c the logic for handling task 1 and task 2 are diff.
must check if pq is empty after polling task 1; if it is, and task 1 still has chars remaining, i must return “”.
https://leetcode.com/problems/longest-happy-string/description/
code and review logic
max heap of CharCounts. must handle case of
if (sb.charAt(sb.length() - 1) == ch && sb.charAt(sb.length() - 2) == ch)
https://leetcode.com/problems/car-pooling/
code and review logic
for loop thru trips array.
first, i get to the position of the new trip. then i drop off all passengers whose end pos is <= curr pos.
then pick up passengers and add new trip to pq. if capacity is exceeded, return false
find median from data stream
don’t code; review logic
- if both heaps are empty, always add to max (smaller half). if num is > max heap peek, add to min; else, add to max
- when finding median, must PEEK, do not poll!
https://leetcode.com/problems/maximum-performance-of-a-team/description/
code and review logic
combine the 2 arrays into 1 Integer array sorted desc by efficiency. min heap based on speed.
as you consider each engineer in each iteration of the loop, polling from the pq must be done BEFORE adding the new speed to the pq
generate parentheses
don’t code; review logic
if (close == 0), add comb to output and return.
if (open > 0), add “(“.
if (close > open), add “)”.
if using sb, must delete last char after each recursive call using sb.setLength(sb.length() - 1) since appending is permanent
https://leetcode.com/problems/daily-temperatures/description/
review while loop
stack of item(temp, idx).
for loop thru temp array.
while stack is not empty and curr temp > stack.peek().temp, pop from stack and edit output arr. after exiting the while loop, add curr temp to stack.
https://leetcode.com/problems/asteroid-collision/description/
just code the while loop
for loop thru input array.
while stack is not empty and prev asteroid is going right and curr asteroid is going left,
compare abs val of the 2 asteroids. do stack.pop() to destroy the prev asteroid and a = 0 to destroy curr asteroid.
after exiting while loop, add a to stack only if it is not 0.
https://leetcode.com/problems/min-stack/description/
don’t code; review logic
just 1 regular stack and 1 min stack.
no need to keep track of min value. if minStack is non-empty, push min(stack.peek(), val); else, just push. when popping, just call pop() on each of the stacks
https://leetcode.com/problems/implement-stack-using-queues/description/
don’t code; review logic
use 1 queue only. all functions are one-liners except push(). for q.size() - 1 times, q.add(q.poll()).
the shifting must be done in push(), not pop(), otherwise top() won’t be implemented correctly.
https://leetcode.com/problems/online-stock-span/description/
don’t code; review logic
each stack item must have span and price
while stack is not empty and price is >= stack.peek().price, span += stack.pop().span
https://leetcode.com/problems/car-fleet/
code and review logic
no need for stack.
combine pos and speed arrays into a single Integer[][] array and sort it by pos in reverse order (bc you want to start w/ the car closest to target).
if you encounter a timeToTarget > TTTofLastFleet add 1 to the number of fleets, and update TTTofLastFleet.
if timeToTarget <= TTTofLastFleet, they would be part of the same fleet.
https://leetcode.com/problems/decode-string/description/
code and review logic
- Stack<StringBuilder> result, from which i get strToRepeat. it must start out with one empty sb</StringBuilder>
- Stack<Integer> kStack</Integer>
- StringBuilder individualK
iterate thru string and handle the 4 cases: digit (use Character.isDigit(ch)), [, ], letter
must result.add(new StringBuilder()) at the beginning (bc there is an imaginary [ at the very beginning) and when you encounter [
https://leetcode.com/problems/remove-k-digits/
code and review logic
since you must remove large numbers in large places, use monotonic non-decreasing stack. same consecutive nums are allowed.
- for loop thru input string. while (k > 0 and stack and digit > stack.peek()), stack.pop()
- take care of remaining k
- get rid of leading 0s by converting stack into string builder (remember to use sb.reverse())
https://leetcode.com/problems/remove-all-adjacent-duplicates-in-string-ii/description/
don’t code; review logic
use stack of Item(letter, count).
for loop thru input string. pop from stack once count reaches k.
at the end, use an sb and sb.reverse() to convert stack into a string
https://leetcode.com/problems/simplify-path/
code and review logic
- get tokens by splitting path using / as delimiter
- go thru tokens array. when comparing, use equals(), not ==. if token is .., pop from stack if valid. only add token if it isn’t “..”, “.”, or “”
- return String.join(“/”, stack). this is where absolute path should be handled