Data Structures & AlgorithmsHardWipro · Accenture pattern
What is the time complexity of this Java method?
What is the time complexity of this Java method?
String build(int n) {
String s = "";
for (int i = 0; i < n; i++)
s = s + "a";
return s;
}- A. O(1)
- B. O(n)
- C. O(n²)
- D. O(n log n)
Correct answer: C. O(n²)
Java Strings are immutable, so each s + "a" copies the current i characters into a new String: 1 + 2 + … + n = n(n + 1)/2 character copies, O(n²). A StringBuilder would make it O(n) amortised.
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
- In Python, a list q is used as a queue: items are added with q.append(x) and removed with q.pop(0). If n items pass through the queue…
- What does this function print for the list 1 → 2 → 3 → 4 → 5 → 6? python def f(node): if node is None: return if node.next…
- slow and fast both start at the head of 1 → 2 → 3 → 4 → 5 → 6. Loop A: while (fast && fast->next) { slow = slow->next; fast =…
- What is the maximum number of comparisons top-down merge sort can make on 8 elements (any input order)?
- What is the minimum number of comparisons needed, in the worst case, to find BOTH the maximum and the minimum of 100 distinct numbers?
- One Lomuto partition (pivot = last element, i marks the end of the 'smaller' part, swap when a[j] < pivot) is applied to [7, 2, 9, 4, 3…