ProgrammingHardCapgemini · TCS NQT
Closed intervals (start, end): (1,4), (2,6), (8,10), (9,12), (11,13), (3,5). The greedy below places points so that every interval contains at least one point. What is printed?
Closed intervals (start, end): (1,4), (2,6), (8,10), (9,12), (11,13), (3,5). The greedy below places points so that every interval contains at least one point. What is printed?
sort intervals by end ascending
last = -infinity; points = 0
for each (s, e) in sorted order
if s > last then last = e; points = points + 1
end for
Print points- A. 3
- B. 6
- C. 5
- D. 2
Correct answer: A. 3
Placing a point at the earliest end covers every interval that starts at or before it, which gives 3 points. Counting intervals gives 6, setting last to the start instead of the end over-counts, and demanding a gap of one unit in the test changes the answer.
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- Job durations (burst times) are 6, 8, 7, 3, 4 with all jobs arriving at time 0. Shortest-job-first runs them one after another in…
- A row of positions 1 to 20 is scanned in order. A position i is picked if no position has been picked yet, or if i minus the last picked…
- Array a = [2,3,1,1,4,2,1,3,1,1] (0-based). From index i you may jump forward at most a[i] positions. Starting at index 0, the greedy below…
- Tasks with the same letter must be separated by at least n = 2 idle or other slots. The task string is AAABBC. The greedy formula below…
- Items of sizes 5, 7, 5, 2, 4, 2, 5, 1, 6 are packed in this order into bins of capacity 10 using the first-fit rule: put each item into…
- Coins are 1, 5, 10, 21 and 25. To pay 63, the greedy method below always takes the largest coin that fits, using the list in descending…