Data Structures Arrays and Strings 1 — Questions and Answers
Question 1: What is the time complexity of accessing an element in an array by index?
- O(n)
- O(log n)
- O(1) (Correct answer)
- O(n²)
Correct answer: O(1)
Array elements are stored in contiguous memory locations, so index-based access is always O(1) constant time.
Question 2: Which array traversal technique uses two pointers moving toward each other from both ends?
- Sliding window
- Two-pointer technique (Correct answer)
- Binary search
- Divide and conquer
Correct answer: Two-pointer technique
The two-pointer technique places one pointer at the start and one at the end, moving them toward each other to solve problems efficiently.
Question 3: What is the worst-case time complexity of searching for an element in an unsorted array?
- O(1)
- O(log n)
- O(n) (Correct answer)
- O(n log n)
Correct answer: O(n)
In the worst case, you must examine every element in an unsorted array, giving O(n) linear time complexity.
Question 4: Which operation is most expensive in a dynamic array when it needs to resize?
- Reading an element
- Appending when capacity is full (Correct answer)
- Accessing the last element
- Checking the length
Correct answer: Appending when capacity is full
When a dynamic array exceeds capacity, all existing elements must be copied to a new larger array, making it an O(n) operation.
Question 5: What does the sliding window technique optimize when processing subarrays or substrings?
- Sorting the array
- Avoiding nested loops by reusing previous computations (Correct answer)
- Reversing the array in place
- Finding the median element
Correct answer: Avoiding nested loops by reusing previous computations
The sliding window technique maintains a running result as the window moves, reducing time complexity from O(n²) to O(n).
Question 6: In a 2D array stored in row-major order, which access pattern is more cache-friendly?
- Column-by-column access
- Random access
- Row-by-row access (Correct answer)
- Diagonal access
Correct answer: Row-by-row access
Row-by-row access is cache-friendly in row-major order because consecutive row elements are stored adjacently in memory.
What is the time complexity of accessing an element in an array by index?