ProgrammingVery hardAmazon OA · Goldman Sachs OA
Strings are immutable here, so s = s + "a" copies the whole current string. What is the time complexity of the following pseudocode, as a function of n?
Strings are immutable here, so s = s + "a" copies the whole current string. What is the time complexity of the following pseudocode, as a function of n?
String s = ""
for (each i from 1 to n)
s = s + "a"
end for- A. O(n²)
- B. O(n)
- C. O(n log n)
- D. O(1)
Correct answer: A. O(n²)
Iteration i copies a string of length i − 1, so the total copying is 0 + 1 + … + (n − 1) ≈ n²/2: O(n²). Using a growable buffer instead brings it down to O(n).
Practise more Pseudocode and Code Tracing questionsPseudocode and Code Tracing: notes and key points
More Pseudocode and Code Tracing questions
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Boolean prime[2..50] //…
- What will be the output of the following pseudocode? Integer count = 0, n = 2, s = 0 while (count < 10) Boolean pr = true for (each d from…
- What will be the output of the following pseudocode? (XOR is true when exactly one side is true; NOT binds tighter than AND, which binds…
- What will be the output of the following pseudocode? Integer a[6] = {3, 8, 1, 9, 4, 7} Integer best = -1, i = 0, j = 5 while (i < j) best…
- What will be the output of the following pseudocode? (All variables are integers, so / is integer division) Integer n = 37, ones = 0…
- What will be the output of the following pseudocode? Integer a[5] = {2, 4, 1, 3, 5}, c = 0 for (each i from 0 to 3) for (each j from i + 1…