Leetcode Practice
Leetcode Practice
= [
([2, 7, 11, 15], 9),
([3, 2, 4], 6),
([3, 3], 6)
]
class ( ):
def ( , , ):
= {}
for , in ( ):
= -
if in :
return [ [ ], ]
[ ] =
class Solution(object):
def twoSum(self, nums, target):
"""
:type nums: List[int]
:type target: int
:rtype: List[int]
"""
lookup = {}
for i, num in enumerate(nums):
complement = target - num
if complement in lookup:
return [lookup[complement], i]
lookup[num] = i
# Fix: Use a list of tuples instead of a dictionary with list keys as list can't be a diction
test_cases = [
([2, 7, 11, 15], 9),
([3, 2, 4], 6),
([3, 3], 6)
]
class ( ):
def ( ,):
"""
:type prices: List[int]
:rtype: int
"""
= ('inf') # Start with a very high minimum
= 0 # Start with zero profit
for in :
if < :
= # Update min_price when a lower price
is found
else:
= -
= ( , ) # Update max_profit
if current profit is higher
return
class Solution:
def maxProfit(self, prices):
min_price = float('inf') # Start with a very high minimum
max_profit = 0 # Start with zero profit
return max_profit
# Fix: Use a list of tuples instead of a dictionary with list keys as list can't be a diction
test_cases = [
[7,1,5,3,6,4],
[7,6,4,3,1]
]
class :
def ( , : [ ]) -> :
= ('-inf')
= 0
for in :
+=
= ( , )
return
class Solution:
def maxSubArray(self, nums):
sum_window = max_window = nums[0]
class Solution:
def maxSubArray(self, nums):
max_sum =float('-inf')
current_sum = 0
for num in nums:
current_sum += num
max_sum = max(current_sum, max_sum)
return max_sum
# Fix: Use a list of tuples instead of a dictionary with list keys as list can't be a diction
test_cases = [
[-2,1,-3,4,-1,2,1,-5,4],
[1], [5,4,-1,7,8]
]
for in :
= ( , )
= ( , - )
return
for in :
= ( , ) # update if we found a lower buying
price
= ( , - ) # update max profit
if today's profit is better
= [7, 1, 5, 3, 6, 4]
= [7,6,4,3,1]
= [
[7,1,5,3,6,4],
[7,6,4,3,1]
]
for in :
= ()
= . ( )
(f"prices : { } => max profit: { }")
class Solution:
def maxProfit(self, prices):
min_price = float('inf')
max_profit = 0
# Fix: Use a list of tuples instead of a dictionary with list keys as list can't be a diction
test_cases = [
[7,1,5,3,6,4],
[7,6,4,3,1]
]
class :
def ( , : ) -> :
= ( )
= {} # Stores the last index where each character was
seen
= 0 # Left pointer of the window
= 0 # Length of the longest substring found
= {}
= 0
= 0
: "abcabcbb"
: 3 # longest is "abc"
class :
def ( , ):
= ()
= 0
= 0
for in ( ( )):
while [ ] in :
. ( [ ])
+= 1
. ( [ ])
= ( , - + 1)
return
class :
def ( , : ) -> :
= ( )
= {} # stores most recent index of each character
= 0 # start of window
= 0
for in ( ):
if [ ] in :
= ( [ [ ]] + 1, ) # move i only forward
= ( , - + 1)
[ [ ]] =
( [ ], )
return
class Solution:
def lengthOfLongestSubstring(self, s):
char_set = set()
left = 0
max_length = 0
return max_length
test_cases = [
"abcabcbb",
"bbbbb",
"pwwkew"
]
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
char_set = set() # 1. To store characters currently in our window
left = 0 # 2. The left edge of our window
max_length = 0 # 3. To keep track of the longest substring found so far
# 4. The 'right' pointer moves from the beginning to the end of the string
for right in range(len(s)):
# 5. Check if the character at the 'right' pointer is already in our current windo
while s[right] in char_set:
# 6. If it is, we need to shrink the window from the left
char_set.remove(s[left]) # Remove the character at the 'left' pointer from our
left += 1 # Move the 'left' pointer one step to the right
# 7. Add the current character (at 'right' pointer) to our window's set
char_set.add(s[right])
# 8. Calculate the current window's length and update max_length if this window is
max_length = max(max_length, right - left + 1)
test_cases = [
"abcabcbb",
"bbbbb",
"pwwkew"
]
class :
def ( , : ) -> :
= () # 1. To store characters currently in our window
= 0 # 2. The left edge of our window
= 0 # 3. To keep track of the longest substring
found so far
class Solution:
def lengthOfLongestSubstring(self, s: str) -> int:
n = len(s)
pos = {}
i = 0
ans = 0
for j in range(n):
if s[j] in pos:
i = max(pos[s[j]]+1, i)
ans = max(ans, j-i+1)
pos[s[j]] = j
print(s[j], ans)
return ans
test_cases = [
"abcabcbb",
"bbbbb",
"pwwkew"
]
( , ) = [ + 1] - [ ]
class :
def ( , ):
. = [0]
for in :
. . ( . [-1] + )
def ( , , ):
return . [ + 1] - . [ ]
class NumArray:
def __init__(self, nums):
self.prefix_sum = [0]
for num in nums:
self.prefix_sum.append(self.prefix_sum[-1] + num)
= [1, 2, 3], = 3
= 0
for in ( ( )):
= 0
for in ( , ( )):
+= [ ]
if == :
+= 1
= [1, 2, 3], = 3
= 0
= 0
= {0: 1} # Important! Base case: sum 0 occurred once
= 1
- = 1 - 3 = -2 → not in
→ =1 → {0:1, 1:1}
= 3
- = 3 - 3 = 0 → in
→ += [0] → = 1
→ =3 → = {0:1, 1:1, 3:1}
= 6
- = 6 - 3 = 3 → in
→ += [3] → = 2
→ =6 → = {0:1, 1:1, 3:1, 6:1}
class :
def ( , : [ ], : ) -> :
= 0
= 0
= {0: 1} # sum 0 occurs once
for in :
+=
if ( - ) in :
+= [ - ]
[ ] = . ( , 0) + 1
return
class Solution:
def subarraySum(self, nums, k):
count = 0
for i in range(len(nums)):
total = 0
for j in range(i, len(nums)):
total += nums[j]
if total == k:
count += 1
class Solution:
def subarraySum(self, nums, k):
prefix_sum = 0
count = 0
prefix_map = {0: 1} # sum 0 occurs once
return count
test_cases = [
([1,1,1], 2),
([1,2,3], 3)
]
class Solution(object):
def subarraySum(self, nums, k):
from collections import defaultdict
prefix_sum = defaultdict(int)
prefix_sum[0] = 1
current_sum = 0
count = 0
return count
test_cases = [
([1,1,1], 2),
([1,2,3], 3)
]
def ():
, = 0, ( ) - 1
= -1
while <= :
= ( + ) // 2
if [ ] < :
= + 1
else:
if [ ] == :
=
= - 1
return
def ():
, = 0, ( ) - 1
= -1
while <= :
= ( + ) // 2
if [ ] > :
= - 1
else:
if [ ] == :
=
= + 1
return
= [5, 7, 7, 8, 8, 10]
= 8
class Solution:
def search(self, nums, target) -> int:
n = len(nums)
left = 0
right = n-1
while left <=right:
mid = (left+right)//2
if nums[mid] == target:
return mid
elif nums[mid] < target:
left = mid +1
else:
right = mid -1
return -1
test_cases = [
([-1,0,3,5,9,12],9),
([-1,0,3,5,9,12],2)
]
= []
[[1, 6], [8, 10], [15, 18]]
class :
def ( , : [ [ ]]) -> [ [ ]]:
. ( =lambda : [0]) # Sort by start time
= []
for in :
if not or [-1][1] < [0]: # No overlap
. ( )
else:
# Overlap: merge with the last one
[-1][1] = ( [-1][1], [1])
return
def findRight():
left, right = 0, len(nums) - 1
index = -1
while left <= right:
mid = (left + right) // 2
if nums[mid] > target:
right = mid - 1
else:
if nums[mid] == target:
index = mid
left = mid + 1
return index
test_cases = [
([5,7,7,8,8,10],8),
([5,7,7,8,8,10],6),
([],0)
]
class Solution:
def merge(self, intervals):
# Step 1: Sort intervals by start time
intervals.sort(key=lambda x: x[0])
merged = []
return merged
test_cases = [
[[1,3],[2,6],[8,10],[15,18]],
[[1,4],[4,5]]
]
class :
def ( , : [ ]) -> [ [ ]]:
. ()
= []
= ( )
for in ( ):
if > 0 and [ ] == [ - 1]:
continue # skip duplicate `i`
, = + 1, - 1
while < :
= [ ] + [ ] + [ ]
if == 0:
. ([ [ ], [ ], [ ]])
+= 1
-= 1
# Skip duplicates for `left` and `right`
while < and [ ] == [ - 1]:
+= 1
while < and [ ] == [ + 1]:
-= 1
elif < 0:
+= 1
else:
-= 1
return
class Solution:
def threeSum(self, nums):
nums.sort()
res = []
n = len(nums)
for i in range(n):
if i > 0 and nums[i] == nums[i - 1]:
continue # skip duplicate `i`
left, right = i + 1, n - 1
while left < right:
total = nums[i] + nums[left] + nums[right]
if total == 0:
res.append([nums[i], nums[left], nums[right]])
left += 1
right -= 1
# Skip duplicates for `left` and `right`
while left < right and nums[left] == nums[left - 1]:
left += 1
while left < right and nums[right] == nums[right + 1]:
right -= 1
elif total < 0:
left += 1
else:
right -= 1
return res
test_cases = [
[-1,0,1,2,-1,-4],
[0,1,1],
[0,0,0]
]
class Solution:
def threeSum(self, nums):
nums=sorted(nums)
n=len(nums)
res=[]
for i in range(n):
if i>0 and nums[i]==nums[i-1]:
continue
j=i+1
k=n-1
while j<k:
sum=nums[i]+nums[j]+nums[k]
if sum<0:
j+=1
elif sum>0:
k-=1
else:
res.append(sorted([nums[i],nums[j],nums[k]]))
j+=1
k-=1
while j<k and nums[j]==nums[j-1]:
j+=1
return res
test_cases = [
[-1,0,1,2,-1,-4],
[0,1,1],
[0,0,0]
]
while < :
= ( [ ], [ ])
= -
= ( , * )
return
= [1,8,6,2,5,4,8,3,7]
return max_area
test_cases = [
[1,8,6,2,5,4,8,3,7],
[1,1]
]
class Solution:
def maxArea(self, height):
left = 0
right = len(height) - 1
max_area = 0
return max_area
test_cases = [
[1,8,6,2,5,4,8,3,7],
[1,1]
]
class :
def ( , : [ ]) -> None:
, , = 0, 0, ( ) - 1
while <= :
if [ ] == 0:
[ ], [ ] = [ ], [ ]
+= 1
+= 1
elif [ ] == 1:
+= 1
else: # nums[mid] == 2
[ ], [ ] = [ ], [ ]
-= 1
= [2, 0, 2, 1, 1, 0]
= [0, 0, 1, 1, 2, 2]
= 0
for in (3):
for in ( [ ]):
[ ] =
+= 1
class Solution:
def sortColors(self, nums):
low, mid, high = 0, 0, len(nums) - 1
return nums
test_cases = [
[2,0,2,1,1,0],
[2,0,1]
]
= [0, 0, 0]
for in :
[ ] += 1
= [2, 0, 2, 1, 1, 0]
= [2, 2, 2] # 2 zeros, 2 ones, 2 twos
= 0
for in (3): # Loop through 0, 1, and 2
for in ( [ ]): # Fill the array with that number count[i]
times
[ ] =
+= 1
= [2, 0, 2, 1, 1, 0]
= [2, 2, 2] # 2 of each
= [0, 0, 1, 1, 2, 2]
# 75. Sort Colors
class Solution:
def sortColors(self, nums):
count = [0, 0, 0]
for num in nums:
count[num] += 1
index = 0
for i in range(3):
for _ in range(count[i]):
nums[index] = i
index += 1
return nums
test_cases = [
[2,0,2,1,1,0],
[2,0,1]
]
class Solution:
def isAnagram(self, s, t) -> bool:
return sorted(s) == sorted(t)
test_cases = [
("anagram","nagaram"),
("rat","cat")
]
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return Counter(s) == Counter(t)
: = "anagram", = "nagaram"
: True
class :
def ( , : , : ) -> :
if [:] == [::-1]: # checks if s is a palindrome
for in :
if . (): # checks if any character is
alphanumeric
return True
return False
class :
def ( , : , : ) -> :
return ( ) == ( )
from import
class :
def ( , : , : ) -> :
return ( ) == ( )
class Solution:
def isAnagram(self, s: str, t: str) -> bool:
return Counter(s) == Counter(t)
from import
class :
def ( , : , : ) -> :
= ( )
= ( )
for in :
if [ ] > . ( , 0):
return False
return True
= "aa"
= ("aa")
# => {'a': 2}
= "aab"
= ("aab")
# => {'a': 2, 'b': 1}
for in :
if [ ] > . ( , 0):
return False
return True
class :
def ( , : , : ) -> :
= [0] * 26 # For 26 lowercase letters
for in :
[ ( ) - ('a')] += 1
for in :
= ( ) - ('a')
[ ] -= 1
if [ ] < 0:
return False
return True
class Solution:
def canConstruct(self, ransomNote, magazine):
ransom_count = Counter(ransomNote)
magazine_count = Counter(magazine)
test_cases = [
("a","b"),
("aa","ab"),
("aa","aab")
]
class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
for char in ransomNote:
if char in magazine:
magazine="".join(magazine.split(char,1))
else:
return False
return True
test_cases = [
("a","b"),
("aa","ab"),
("aa","aab")
]
class :
def ( , : ) -> :
= ''. ( . () for in if . ())
return == [::-1]
= "A man, a plan, a canal: Panama"
(). ( ) # Output: True
class Solution:
def isPalindrome(self, s: str) -> bool:
clean_s = ''.join(char.lower() for char in s if char.isalnum())
return clean_s == clean_s[::-1]
test_cases = [
"A man, a plan, a canal: Panama",
"race a car",
" "
]
= ""
for in ( ( )):
# Odd length palindrome
= ( , )
if ( ) > ( ):
=
return
= "babad"
(). ( ) # Output: "bab" or "aba"
class Solution:
def longestPalindrome(self, s: str) -> str:
def expand_around_center(left: int, right: int) -> str:
while left >= 0 and right < len(s) and s[left] == s[right]:
left -= 1
right += 1
return s[left + 1:right]
longest = ""
for i in range(len(s)):
# Odd length palindrome
odd_pal = expand_around_center(i, i)
if len(odd_pal) > len(longest):
longest = odd_pal
return longest
test_cases = [
"babad",
"cbbd",
" "
]
class Solution:
def longestPalindrome(self, s: str) -> str:
res = [0, 0]
n = len(s)
start = 0
while n-start > (res[1]-res[0])//2:
head = start+1
tail = start-1
while head<n and s[head]==s[start]:
head += 1
while head<n and tail>=0 and s[tail] == s[head]:
head += 1
tail -= 1
if head-tail-1>res[1]-res[0]:
res = [tail+1, head]
start += 1
return s[res[0]:res[1]]
test_cases = [
"babad",
"cbbd",
" "
]
def count_consecutive_binary_groups(lst):
count = -1
prev = None
for x in lst:
if x != prev:
count += 1
prev = x
return count + 1 # Ensures single-element list returns 1
def test_count_consecutive_binary_groups():
assert count_consecutive_binary_groups([]) == 0
assert count_consecutive_binary_groups([1]) == 1
assert count_consecutive_binary_groups([0]) == 1
assert count_consecutive_binary_groups([0, 0, 0]) == 1
assert count_consecutive_binary_groups([1, 1, 0]) == 2
assert count_consecutive_binary_groups([1, 0, 1]) == 3
assert count_consecutive_binary_groups([0, 1, 1, 1, 0]) == 3
assert count_consecutive_binary_groups([1, 0, 0, 1, 1, 0]) == 4
assert count_consecutive_binary_groups([1, 1, 1, 1, 1]) == 1
assert count_consecutive_binary_groups([0, 1, 0, 1, 0, 1]) == 6
test_count_consecutive_binary_groups()
def count_consecutive_binary_groups(lst):
# Ensure only 0 and 1 are allowed
count = -1
prev = None
for x in lst :
if x != prev and x in (0,1):
count += 1
prev = x
return max(count + 1, 0) # Ensures single-element list returns 1
def test_count_consecutive_binary_groups():
assert count_consecutive_binary_groups([]) == 0
assert count_consecutive_binary_groups([1]) == 1
assert count_consecutive_binary_groups([0]) == 1
assert count_consecutive_binary_groups([0, 0, 0]) == 1
assert count_consecutive_binary_groups([1, 1, 0]) == 2
assert count_consecutive_binary_groups([1, 0, 1]) == 3
assert count_consecutive_binary_groups([0, 1, 1, 1, 0]) == 3
assert count_consecutive_binary_groups([1, 0, 0, 1, 1, 0]) == 4
assert count_consecutive_binary_groups([1, 1, 1, 1, 1]) == 1
assert count_consecutive_binary_groups([0, 1, 0, 1, 0, 1]) == 6
assert count_consecutive_binary_groups([0, 1, 0, 1, 0, 1,1,2,3]) == 6
print("All test cases passed!")
test_count_consecutive_binary_groups()
def count_consecutive_binary_groups_str(s):
count = -1
prev = None
for char in s:
if char in ('0', '1') and char != prev:
count += 1
prev = char
return max(count + 1, 0) # Ensure 0 for empty input
def test_count_consecutive_binary_groups_str():
assert count_consecutive_binary_groups_str("") == 0
assert count_consecutive_binary_groups_str("1") == 1
assert count_consecutive_binary_groups_str("0") == 1
assert count_consecutive_binary_groups_str("000") == 1
assert count_consecutive_binary_groups_str("110") == 2
assert count_consecutive_binary_groups_str("101") == 3
assert count_consecutive_binary_groups_str("01110") == 3
assert count_consecutive_binary_groups_str("100110") == 4
assert count_consecutive_binary_groups_str("11111") == 1
assert count_consecutive_binary_groups_str("010101") == 6
assert count_consecutive_binary_groups_str("01010112ab3") == 6 # ignoring non-binary cha
test_count_consecutive_binary_groups_str()
# Create a function that can return the prime numbers up to a given number n.
# The function should be named `get_primes` and take one argument, n.
# It should return a list of prime numbers up to n (inclusive).
# A prime number is a natural number greater than 1 that cannot be formed by multiplying two
# The first few prime numbers are: 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, etc.
# The function should handle edge cases, such as when n is less than 2, in which case it shou
# The function should also be efficient and not use brute force methods to check for primalit
# The function should be able to handle large values of n efficiently.
def get_primes(n):
"""Return a list of prime numbers up to n (inclusive)."""
if n < 2:
return []
primes = []
is_prime = [True] * (n + 1)
is_prime[0] = is_prime[1] = False # 0 and 1 are not prime numbers
return primes
def get_primes(n):
if n < 2:
return []
return primes
def partial_sum(n):
"""Return the sum of the first n prime numbers."""
primes = get_primes(n)
primes_partial_sum = []
primes_partial_sum[0] = primes[0]# Initialize the first element to 0
for i in range1(1, primes):
primes_partial_sum.append(primes_partial_sum[i-1] + primes[i])
return primes_partial_sum
# Test the function with a few examples
print(get_primes(10)) # Output: [2, 3, 5, 7]
print(get_primes(20)) # Output: [2, 3, 5, 7, 11, 13, 17, 19]
def get_primes(n):
# Step 1: Create a boolean array "is_prime[0..n]" and initialize all entries as True
is_prime = [True] * (n + 1)
p = 2
# Step 2: Set 0 and 1 as non-prime
is_prime[0] = is_prime[1] = False
return primes_partial_sum
# Test the function with a few examples
print(get_primes(10)) # Output: [2, 3, 5, 7]
print(get_primes(20)) # Output: [2, 3, 5, 7, 11, 13, 17, 19]
def max_subarray_sum(arr):
"""Return the maximum sum of a contiguous subarray."""
max_sum = float('-inf')
current_sum = 0
return max_sum
# Test the function with a few examples
print(max_subarray_sum([-2,1,-3,4,-1,2,1,-5,4])) # Output: 6 (subarray [4,-1,2,1])
def minimum_subarray_sum(arr):
"""Return the minimum sum of a contiguous subarray."""
min_sum = float('inf')
current_sum = 0
return min_sum
# Test the function with a few examples
print(minimum_subarray_sum([2,-1,3,-4,5,-2])) # Output: -4 (subarray [-4])
print(minimum_subarray_sum([-2,1,-3,4,-1,2,1,-5,4])) # Output: -6 (subarray [-2,1,-3])
def max_sum_subarray_partial_sums(arr):
"""Return the maximum sum of a contiguous subarray using partial sums."""
n = len(arr)
partial_sums = [0] * (n + 1)
max_sum = float('-inf')
min_partial_sum = float('inf')
#stopHere
def has_binary_alternating_subseq(arr):
if arr is None or len(arr) == 0:
return False
max_length = 0
i = 0
arr = [20,15,3,5,10,19,23,30,100]
def selection_sort(arr):
for i in range(len(arr)):
for j in range(i+1,len(arr)):
if arr[i] > arr[j]:
arr[i], arr[j] = arr[j], arr[i]
return arr
solution = selection_sort(arr)
print(solution)
arr = [20,15,3,5,10,19,23,30,100]
def selection_sort(arr):
for i in range(len(arr)):
smallest_index = i
for j in range(i+1,len(arr)):
if arr[j] < arr[smallest_index]:
smallest_index = j
arr[i], arr[smallest_index] = arr[smallest_index], arr[i]
return arr
solution = selection_sort(arr)
print(solution)
arr = [20,15,3,5,10,19,23,30,100]
new_arr = []
def find_smallest(arr):
smallest_item = arr[0]
smallest_index = 0
for i in range(1, len(arr)):
if arr[i] < smallest_item:
smallest_item = arr[i]
smallest_index = i
return smallest_index
def selection_sort(arr):
new_arr = []
for i in range(len(arr)):
smallest = find_smallest(arr)
new_arr.append(arr.pop(smallest))
return new_arr
solution = selection_sort(arr)
print(solution)
def find_smallest(arr):
smallest_item = arr[0]
smallest_index = 0
for i in range(1, len(arr)):
if arr[i] < smallest_item:
smallest_item = arr[i]
smallest_index = i
return smallest_index
def selection_sort(arr):
new_arr = []
while arr:
smallest = find_smallest(arr)
new_arr.append(arr.pop(smallest))
return new_arr
solution = selection_sort(arr)
print(solution)
arr = [20,15,3,5,10,19,23,30,100]
def selection_sort(arr):
for i in range(len(arr)):
largest_index = i
for j in range(i+1,len(arr)):
if arr[j] > arr[largest_index]:
largest_index = j
arr[i], arr[largest_index] = arr[largest_index], arr[i]
return arr
solution = selection_sort(arr)
print(solution)
def count(n):
for i in range(n):
print(i)
count(5)
def count(n):
if n <= 0:
return
print(n)
count(n - 1)
count(5)
def countdown(i):
print(i)
if i <= 0:
return
else:
countdown(i-1)
count(5)
def sum_(arr):
if len(arr) == 0:
return 0
else:
return arr[0] + sum_(arr[1:])
arr = [20,15,3,5,10,19,23,30,100]
solution = sum_(arr)
print(solution)
def count_items(arr):
if len(arr) == 0:
return 0
else:
return 1 + count_items(arr[1:])
def max_num(arr):
if len(arr) == 0:
return float('-inf') # or raise an exception if empty lists are invalid
elif len(arr) == 1:
return arr[0]
else:
sub_max = max_num(arr[1:])
return arr[0] if arr[0] > sub_max else sub_max
arr = [20, 15, 3, 5, 10, 19, 23, 30, 100]
solution = max_num(arr)
print(solution) # Output:
if arr[mid] == target:
return mid # Base case: target found
elif arr[mid] > target:
return binary_search(arr, target, low, mid - 1) # Recursive case: left half
else:
return binary_search(arr, target, mid + 1, high) # Recursive case: right half
def quick_sort(arr):
if len(arr) < 2:
return arr # Base case: already sorted
else:
pivot = arr[0]
less = [x for x in arr[1:] if x <= pivot]
greater = [x for x in arr[1:] if x > pivot]
return quick_sort(less) + [pivot] + quick_sort(greater)
quick_sort(arr)
def merge_sort(arr):
if len(arr) <= 1:
return arr # Base case: already sorted
mid = len(arr) // 2
left_half = merge_sort(arr[:mid])
right_half = merge_sort(arr[mid:])
return result
# Example usage:
arr = [10, 5, 2, 3]
print(merge_sort(arr)) # Output: [2, 3, 5, 10]
return menu