Data Structures & AlgorithmsHardProduct Company SDE pattern
What is printed? (next greater element to the right, −1 if none)
What is printed? (next greater element to the right, −1 if none)
a = [4, 5, 2, 25, 7, 8]
res, st = [-1] * len(a), []
for i in range(len(a) - 1, -1, -1):
while st and st[-1] <= a[i]: st.pop()
res[i] = st[-1] if st else -1
st.append(a[i])
print(res)- A. [5, 25, 25, -1, 8, -1]
- B. [5, 25, 25, -1, 8, 8]
- C. [5, 25, 7, -1, 8, -1]
- D. [5, 5, 25, -1, 8, -1]
Correct answer: A. [5, 25, 25, -1, 8, -1]
Scanning from the right, the stack keeps candidates in decreasing order; smaller or equal values are popped because they can never be the answer for anything further left. 2's next greater is 25 (not 7, which is further right). O(n).
Practise more Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questionsArrays, Strings, Linked Lists, Stacks, Queues and Hashing: notes and key points
More Arrays, Strings, Linked Lists, Stacks, Queues and Hashing questions
- Hash map counting: what is printed? (first element that repeats, scanning left to right) python def firstrepeat(a): seen = set() for x in…
- What is printed? (anagram check two ways) python from collections import Counter x, y = "listen", "enlists" print(sorted(x) == sorted(y)…
- Binary search: how many iterations does this loop run to find x = 23? python a = [2, 5, 8, 12, 16, 23, 38, 56, 72, 91] lo, hi, it = 0…
- What is printed? (run-length decode then re-encode) python import re enc = "a3b1c12" dec = "".join(ch int(n) for ch, n in…
- What is printed? (move zeros to the end keeping order) python a = [0, 1, 0, 3, 12, 0, 5] w = 0 for r in range(len(a)): if a[r] != 0: a[w]…
- What is the time complexity of deleting the last node of a singly linked list of n nodes when only a head pointer is kept?