May 5, 2025
[1, 2, 3, 4, 5], the left rotated array is [2, 3, 4, 5, 1].# Pseudocode
def leftRotate(arr):
temp = arr[0] # Store the first element
for i in range(1, len(arr)):
arr[i-1] = arr[i] # Shift elements left
arr[-1] = temp # Place the first element at the end
D positions.D=2, the array [1, 2, 3, 4, 5] becomes [3, 4, 5, 1, 2].D = D % N to handle cases where D is greater than array size.N-D, then reverse the last D, and finally reverse the entire array.# Pseudocode
def leftRotateByD(arr, D):
D = D % len(arr) # Handle D greater than N
reverse(arr, 0, len(arr)-1)
reverse(arr, 0, len(arr)-D-1)
reverse(arr, len(arr)-D, len(arr)-1)
[0, 1, 0, 3, 12] becomes [1, 3, 12, 0, 0].# Pseudocode
def moveZeros(arr):
lastNonZero = 0
for i in range(len(arr)):
if arr[i] != 0:
arr[lastNonZero], arr[i] = arr[i], arr[lastNonZero]
lastNonZero += 1
# Pseudocode
def linearSearch(arr, target):
for i in range(len(arr)):
if arr[i] == target:
return i
return -1
# Pseudocode
def union(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
elif arr1[i] > arr2[j]:
result.append(arr2[j])
j += 1
else:
result.append(arr1[i]) # or arr2[j]
i += 1
j += 1
return result
# Pseudocode
def intersection(arr1, arr2):
i = j = 0
result = []
while i < len(arr1) and j < len(arr2):
if arr1[i] < arr2[j]:
i += 1
elif arr1[i] > arr2[j]:
j += 1
else:
result.append(arr1[i])
i += 1
j += 1
return result