Skip to content

Instantly share code, notes, and snippets.

@EssamWisam
Created February 12, 2025 05:39
Show Gist options
  • Save EssamWisam/5fe781d6704ea7461f05cd967eaebba2 to your computer and use it in GitHub Desktop.
Save EssamWisam/5fe781d6704ea7461f05cd967eaebba2 to your computer and use it in GitHub Desktop.
Algorithms Hands-on
def fib(n, depth=0):
indent = " " * depth # Indentation for better visualization
print(f"{indent}fib({n}) called")
if n == 0:
print(f"{indent}Returning 0")
return 0
if n == 1:
print(f"{indent}Returning 1")
return 1
result = fib(n - 1, depth + 1) + fib(n - 2, depth + 1)
print(f"{indent}Returning {result} from fib({n})")
return result
def merge_two_sorted_arrays(arr1, arr2):
"""Merges two sorted arrays into a single sorted array."""
i, j = 0, 0
merged = []
while i < len(arr1) and j < len(arr2):
if arr1[i] < arr2[j]:
merged.append(arr1[i])
i += 1
else:
merged.append(arr2[j])
j += 1
# Add remaining elements, if any
while i < len(arr1):
merged.append(arr1[i])
i += 1
while j < len(arr2):
merged.append(arr2[j])
j += 1
return merged
def merge_k_sorted_arrays(arrays):
"""Merges K sorted arrays into a single sorted array."""
if not arrays:
return []
merged_array = arrays[0]
for i in range(1, len(arrays)):
merged_array = merge_two_sorted_arrays(merged_array, arrays[i])
return merged_array
# Example usage:
arrays = [
[1, 3, 5, 7],
[2, 4, 6, 8],
[0, 9, 10, 11]
]
result = merge_k_sorted_arrays(arrays)
print(result) # Output: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11]
def remove_duplicates(array):
# Check if the array is empty
if not array:
return []
# Initialize the result array with the first element
result = [array[0]]
# Traverse the array from the second element onwards
for i in range(1, len(array)):
# If the current element is different from the last added element
if array[i] != array[i - 1]:
result.append(array[i])
return result
# Example usage
array1 = [2, 2, 2, 2, 2]
array2 = [1, 2, 2, 3, 4, 4, 4, 5, 5]
print(remove_duplicates(array1)) # Output: [2]
print(remove_duplicates(array2)) # Output: [1, 2, 3, 4, 5]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment