๐ 18. How do you merge two sorted arrays?
๐น Python Solution
def merge(arr1, arr2):
i = j = 0
result = []
while i < len(arr1) and j < len(arr2):
if arr1[i] < arr2[j]:
result.append(arr1[i])
i += 1
else:
result.append(arr2[j])
j += 1
result.extend(arr1[i:])
result.extend(arr2[j:])
return result
print(merge([1,3,5], [2,4,6]))
๐น Output
[1][2][3][4][5][6]
๐น Complexity
Time โ O(n + m)
Space โ O(n + m)
๐น Interview Tip
This is the foundation of Merge Sort.
๐ 19. How do you find the longest substring without repeating characters?
๐น Sliding Window + HashSet
def longest_substring(s):
char_set = set()
left = 0
max_len = 0
for right in range(len(s)):
while s[right] in char_set:
char_set.remove(s[left])
left += 1
char_set.add(s[right])
max_len = max(max_len, right - left + 1)
return max_len
print(longest_substring("abcabcbb"))
๐น Output
3
Substring:
"abc"
๐น Complexity
Time โ O(n)
Space โ O(n)
๐น Interview Tip
Very frequently asked in FAANG interviews.
๐ 20. How do you implement a circular buffer?
A circular buffer reuses empty spaces efficiently.
๐น Visualization
[1, 2, 3, _, _]
After removal:
[_, 2, 3, _, _]
Next insert goes to empty slot.
๐น Python Implementation
class CircularBuffer:
def init(self, size):
self.buffer = [None] * size
self.size = size
self.head = 0
self.tail = 0
self.count = 0
def enqueue(self, value):
if self.count == self.size:
return "Buffer Full"
self.buffer[self.tail] = value
self.tail = (self.tail + 1) % self.size
self.count += 1
def dequeue(self):
if self.count == 0:
return "Buffer Empty"
value = self.buffer[self.head]
self.head = (self.head + 1) % self.size
self.count -= 1
return value
๐น Uses
- Streaming systems
- Audio processing
- Producer-consumer problems
- Network buffers
๐น Complexity
Enqueue โ O(1)
Dequeue โ O(1)
๐ฅ Double Tap โค๏ธ For Part-3
Post #2955
969
- โค 4