CAREER DEVELOPMENT
SERVICES CELL
CDP 07 - TCS NQT TRAINING
DATE: 22.06.2025
FN TOPIC: FOR LOOP, WHILE LOOP, DO-WHILE LOOP, SWITCH STATEMENT
AN TOPIC: TIME & SPACE COMPLEXITY, INTRODUCTION TO DSA, ARRAYS (1D
& 2D), TWO POINTER, SLIDING WINDOW, STRINGS, STRINGBUILDER, PATTERN
MATCHING (INCLUDING LOGICAL PROBLEMS), LINKED LIST (SINGLY,
DOUBLY, CIRCULAR) + PRACTICE, SORTING: BUBBLE, SELECTION, INSERTION,
BIT MANIPULATION (BASICS)
1. For Loop / While Loop / Do-While Loop / Switch Statement
1. For loop – logarithmic steps: Print successive powers of 2 ≤ N using a for loop that
multiplies by 2 each iteration; ensure O(log N) iterations.
2. While loop – digit analysis: Given N, use while (N > 0) to extract digits, determine and
count how many are prime.
3. Do-while – input validation: Use a do-while loop to repeatedly ask for a positive integer
until valid; track attempts.
4. For loop with continue: Traverse array A, sum only even-indexed values (skip others),
without using conditional statements inside the loop body.
5. Nested for loops: Given N, print Pascal’s triangle up to row N using nested loops and no
library functions.
6. Switch – modulo cases: For integers −2 ≤ x ≤ 2, use a switch on x+2 to classify as negative,
zero, or positive.
7. Switch‐in‐range hack: Convert if (score >=90) ... else if(...) logic into a switch(true) or its
equivalent in C/C++.
8. While – reversing linked list simulation: Use while plus array indices to simulate pointer
reversal in a singly linked list.
9. Do-while – string trimming: Remove trailing digits from a string using a do-while until last
char is non-digit.
10. For loop flow-control: Given an array, use a for loop and break to find first repeating
element; print its index or −1.
2. Time & Space Complexity / Introduction to DSA
1. Identify complexity: Analyze nested loops with i*=2 and j+=i, determine time complexity.
2. Space optimization: Convert a recursive factorial function to iterative O(1) space and discuss
time trade-off.
3. Complexity proof: Prove O(n log n) time for merging two sorted subarrays of lengths n/2
each.
4. DSA structure choice: Choose between array, linked list, stack, or queue to implement LRU
cache—you must justify O(1) updates and evictions.
5. Amortized analysis: Show why dynamic array push-back costs amortized O(1) despite
occasional O(n) reallocations.
6. Hash vs BST: Compare average/worst time complexities for search of hash table vs balanced
BST; include space overhead.
7. Recurrence relation: Solve T(n)=T(n−1)+O(1) and T(n)=2T(n/2)+O(n) and identify the
algorithms they represent.
8. Trade-offs: Discuss when to favor space over time—e.g., DP memoization vs plain
recursion.
9. Optimal data struct design: Design a structure for median maintenance with O(log n)
insertion and O(1) median retrieval.
10. Cache effect: Explain how time complexity measured in CPU cycles may differ from
theoretical O(n) due to cache misses.
3. 1D & 2D Arrays
1. Rotate 2D matrix: In-place rotate N×N matrix 90° clockwise.
2. Zero-matrix rows/cols: Given M×N matrix, if a cell is 0, set its entire row and column to 0
with O(1) extra space.
3. Longest histogram rectangle: In a row of heights, compute maximum rectangle area using a
stack in O(N).
4. Triplet sum zero: Find all unique triplets in 1D array that sum to zero in O(N²).
5. Submatrix sum equals target: Given matrix and target, find one submatrix whose sum
equals target (use prefix sums).
6. Spiral traversal: Print elements in spiral order with edge-case handling for single row/col.
7. Rotate right by k: In 1D array, rotate elements to the right by k spots in-place using reversal.
8. Find median in sorted rows: Matrix with each row sorted and equal length; find overall
median in O(N log M).
9. Island counting: In binary 2D grid, count connected regions (4-directional) of 1s with
DFS/BFS.
10. Dynamic row convolution: Given kernel [1,0,−1], apply convolution across each row of an
image matrix.
4. Two-Pointer / Sliding Window
1. Two-sum pairs in sorted array: Count all unique pairs summing to target T.
2. Triplet sum smaller: Count triplets with sum < target using two-pointer inside for-loop.
3. Min window substring: Find smallest substring of S containing all chars of T using sliding
window + hash map.
4. Max subarray K elements: Given N-sized array and K, find max-sum subarray of size ≤ K.
5. Longest non-repeating substring: Using sliding window, find max-length substring without
repeating chars.
6. Subarray with sum divisible by k: Count subarrays where sum mod k == 0 (use prefix +
hashmap window).
7. Sorted squares merge: Merge two sorted arrays of negatives/positives into sorted squared
values in O(n).
8. Min diff pairs with constraint: From sorted arr, find k pairs with minimal absolute
difference.
9. Longest subarray with at most two values: Unique constraint sliding window with dynamic
shrink.
10. Max fruits in k baskets: Given array representing fruits, max contiguous fruits with ≤ k
distinct values.
5. Strings / StringBuilder
1. In-place deduplication: Remove repeated chars keeping first occurrence using only O(1)
buffer.
2. StringBuilder replace: Given a substring to delete, use StringBuilder logic to remove
multiple occurrences without new strings.
3. Anagram grouping: Group list of strings into anagram buckets using sorted character keys.
4. Palindrome partitioning: Generate all palindrome partition substrings using backtracking.
5. Minimum window palindrome: Given string, find shortest insertion to make palindrome.
6. Reverse words in a sentence: Without built-in reverse, use StringBuilder to reverse order of
words.
7. URLify: Replace spaces with %20 in-place on a char array, given true length.
8. Run-length encoding/decoding: Compress then decompress string using StringBuilder.
9. Pattern isomorphic check: Check if two strings are isomorphic using character maps.
10. Word wrap DP: Given string and max line width, break lines minimizing raggedness via
dynamic programming.
6. Pattern Matching / Logical Problems
1. Wildcard match (single ?): Support ? wildcard in pattern matching in O(N·M).
2. KMP search: Implement KMP to return all match starting indices in text.
3. Rabin–Karp duplicates: Find if any substring of length L occurs ≥ 2 times efficiently via
hash + map.
4. Wildcard * allowed once: Pattern may have one *; match text in O(N) time.
5. Logical puzzle – light switches: Given 3 switches and 3 bulbs (one way wiring), determine
switch–bulb mapping with ≤2 operations.
6. Grid word search: Given char matrix and word list, find words present by traversing
neighbors (Trie + DFS).
7. Pattern – “abba” structure: Given string s, check if it follows pattern “abba” (e.g.
‘redbluebluered’).
8. Non-overlapping substrings count: Count non-overlapping occurrences of substr in text.
9. Binary pattern packing: Given binary string, find min start positions to flip to avoid “00” in
result.
10. Suffix array substring: Build suffix array and find k-th lex suffix of a string.
7. Linked List (Singly, Doubly, Circular)
1. Reverse singly list: In-place reverse; return new head.
2. Detect & remove loop: Use Floyd’s cycle detect and remove loop restoring properly.
3. Merge two sorted lists: Without extra nodes, in-place merge sorted singly lists.
4. Reverse in k-groups: Reverse nodes in groups of k; if leftover <k, leave as is.
5. Copy doubly list: Deep-copy a doubly linked list with random pointers if included.
6. Rotate circular list: Given circular list, rotate right by k positions.
7. Delete Nth from end: One-pass two-pointer deletion in singly list.
8. Check palindrome list: Determine if singly list reads the same forward/backward in O(n)
and O(1) space.
9. Flatten multilevel list: Linked list where nodes may have child pointers—flatten into single-
level.
10. Sort linked list: Merge sort for singly linked list in O(n log n) time and constant extra space.
8. Sorting: Bubble / Selection / Insertion
1. Bubble sort early exit: Optimize to detect early sorted array.
2. Selection on list: Perform selection sort on singly linked list by node swapping only.
3. Insertion in adaptive way: Count total shifts made by insertion sort, and optimize using
binary search.
4. Bubble worst-case proof: Given reversed array, count number of comparisons and swaps
exactly.
5. Insertion sort on nearly-sorted: Show time ≈ O(n + k), where k is swaps needed.
6. Simulate shell sort passes: Use gap sequence [N/2, N/4, …, 1] and track moves.
7. Stable versus unstable: Demonstrate unstable behavior on duplicate keys and enforce
stability.
8. Counting sort adaptation: Adapt counting sort for characters ‘a’–‘z’.
9. Odd-even sort merge: Implement odd-even sort (brick sort) and prove O(n²).
10. Online insertion sort: Maintain sorted list by inserting one element at a time (simulate
streaming input).
9. Bit Manipulation (Basics)
1. Check power of two: if ((n & (n−1)) == 0) —explain and test edge cases.
2. Count set bits: Implement Brian Kernighan’s method in O(#bits set).
3. Swap even/odd bits: Given 32-bit, swap adjacent bits using masks and shifts.
4. Single number in triple array: Every number appears thrice except one; find unique one.
5. Reverse bits: Reverse bits of 32-bit integer in O(log W) by bitwise swaps.
6. Gray code conversion: Given n-bit integer, compute corresponding Gray code and inverse.
7. Leading zero count: Find number of leading zeros in unsigned int using bit tricks.
8. Add without ‘+’ operator: Compute a + b using only bitwise operators.
9. Extract lowest set bit: x & (−x) returns lowest 1-bit; test and explain.
10. Parity check: Compute parity (odd/even bits) quickly with XOR tree method.