Skip to content
CodeKruPro

Build a growable list from scratch

Coding problemMediumAsked in: Cognizant

Build a list that grows as values are added, the way the built-in growable lists work inside. Store the values in a fixed-size block of slots; when the block is full, make a new block with more room and copy the values across. Do not use a ready-made growable list.

Your function receives a list of commands and runs them in order on an empty list. Positions count from 0.

  • "add x" puts the value x at the end;
  • "get i" outputs the value at position i;
  • "remove i" removes the value at position i, outputs it, and moves every later value one place forward;
  • "size" outputs how many values the list holds.

If position i does not exist, "get i" and "remove i" output -1 and change nothing. Return all outputs, in order. The hidden tests check the results and the speed: a block that grows by one slot on every add is too slow for 300,000 commands.

Examples

Example 1
Input: commands = ["add 5","add 7","get 1","size"]
Output: [7,2]
Example 2
Input: commands = ["add 1","add 2","add 3","remove 0","get 0","size"]
Output: [1,2,2]
Example 3
Input: commands = ["get 0","remove 3","size"]
Output: [-1,-1,0]

Constraints

  • Between 1 and 300,000 commands
  • Every added value is between 0 and 1,000,000,000
  • Every position i is between 0 and 300,002

Run checks the 3 examples. Submit also runs the hidden tests: edge cases, large inputs and a time limit.

Run your code to see the results here.

This question is part of Pro+

Pro+ opens every question in Interview Prep and the mock interview. Every article and the first 2 questions of each topic stay free. Hands-on Selenium and API tasks follow their course lesson's own lock.

See Pro+

Already have Pro+? Sign in