Data Structures & AlgorithmsHardAmazon · Microsoft OA
Problem: Remove every interval that is covered by another interval ([a, b] is covered by [c, d] if c ≤ a and b ≤ d); count those that remain.
Problem: Remove every interval that is covered by another interval ([a, b] is covered by [c, d] if c ≤ a and b ≤ d); count those that remain.
def remaining(iv):
iv.sort(key=lambda x: (x[0], -x[1])); cnt = 0; end = -1
for s, e in iv:
if e > end: cnt += 1; end = e
return cnt
print(remaining([[1, 4], [3, 6], [2, 8], [1, 8], [9, 10], [9, 9]]))What is printed?- A. 2
- B. 4
- C. 3
- D. 5
Correct answer: A. 2
Sorting by start ascending and end descending puts a covering interval before the ones it covers. [1,8] covers [1,4], [2,8] and [3,6]; [9,10] covers [9,9]. Remaining: [1,8] and [9,10] → 2.
More Coding Interview Problems questions
- Problem: Delete the fewest characters from a string of a's and b's so that no 'b' comes before an 'a'. python def mindel(s): bseen = dels…
- Problem: Add two 32-bit integers without + or −, using XOR for the sum and AND-shift for the carry; Python needs explicit masking to…
- Problem: Validate a byte sequence as UTF-8 (a 1-byte char starts 0xxxxxxx; an n-byte char starts with n 1s and a 0, followed by n − 1…
- Problem: The infinite string 123456789101112… is indexed from 1. Find the n-th digit by skipping whole blocks of 1-digit, 2-digit, ……
- Problem: Compute a^b mod 1337 where the exponent b is given as a digit array (too large for an integer), using a^(10x + d) = (a^x)^10 ·…
- A stack supports push, pop and multipop(k) (pop up to k elements). Starting from empty, what is the worst-case total cost of any sequence…