Data Structures & AlgorithmsModerateCognizant · Capgemini pattern
What is printed? (balanced brackets with a counter only)
What is printed? (balanced brackets with a counter only)
def by_counter(s):
c = 0
for ch in s:
c += 1 if ch == '(' else -1
if c < 0: return False
return c == 0
print(by_counter("(()())"), by_counter("())(()"), by_counter(")("))- A. True True False
- B. True False True
- C. True False False
- D. False False False
Correct answer: C. True False False
With a single bracket type a counter suffices: it must never go negative and must end at 0. "())(()" dips to −1 after the third character. With several bracket types a stack is required, because "([)]" has balanced counts but wrong nesting.
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
- What is printed? (string rotation check) python def isrot(a, b): return len(a) == len(b) and b in a + a print(isrot("waterbottle"…
- What is printed? (sliding window: count subarrays with product less than k, positive values) python def countprod(a, k): if k <= 1: return…
- What is printed? (Java: == vs equals on Strings) java String a = "hello"; String b = "hel" + "lo"; String c = new String("hello"); String…
- What is printed? (expected probes in a hash table) python alpha = 0.75 chaining = 1 + alpha / 2 linearhit = 0.5 (1 + 1 / (1 - alpha))…
- What is printed? (reverse a sublist of a linked list between positions m and n, 1-based) python def revbetween(a, m, n): a = a[:] a[m…
- What is printed? (min-heap array after inserts) python import heapq h = [] for x in [9, 4, 7, 1, 8, 2]: heapq.heappush(h, x) print(h…