0% found this document useful (0 votes)
7 views67 pages

Python Solutions for Common Algorithms

Uploaded by

Temo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views67 pages

Python Solutions for Common Algorithms

Uploaded by

Temo
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

= {[2,7,11,15] : 9, [3,2,4]: 6, [3,3]: 6}

= [
([2, 7, 11, 15], 9),
([3, 2, 4], 6),
([3, 3], 6)
]

class ( ):
def ( , , ):
= {}
for , in ( ):
= -
if in :
return [ [ ], ]
[ ] =

# List of test cases: each is a tuple of (nums list, target)


= [
([2, 7, 11, 15], 9),
([3, 2, 4], 6),
([3, 3], 6)
]

# Run each test


for , in :
= ()
= . ( , )
(f"Input: { }, Target: { } => Output: { }")
for , in ( ):
= -
if in :
return [ [ ], ]
[ ] =
{3: 0, 2: 1}

[1, 2] # because nums[1] + nums[2] == 2 + 4 == 6

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)
]

# Run test cases


for nums, target in test_cases:
solution = Solution()
result = [Link](nums, target)
print(f"Input: {nums}, Target: {target} => Output: {result}")

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

for price in prices:


if price < min_price:
min_price = price # Update min_price when a lower price is found
else:
profit = price - min_price
max_profit = max(max_profit, profit) # Update max_profit if current profit i

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]
]

# Run test cases


for prices in test_cases:
solution = Solution()
result = [Link](prices)
print(f"prices list: {prices} => max profit: {result}")

class :
def ( , : [ ]) -> :
= ('-inf')
= 0

for in :
+=
= ( , )

# Reset current_sum if it drops below 0


if < 0:
= 0

return
class Solution:
def maxSubArray(self, nums):
sum_window = max_window = nums[0]

for num in nums[1:]:


if sum_window < 0:
sum_window = num
else:
sum_window += num
if sum_window > max_window:
max_window = sum_window
return max_window

# Run test cases


for nums in test_cases:
solution = Solution()
result = [Link](nums)
print(f"nums : {nums} => max sub-array: {result}")

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)

# Reset current_sum if it drops below 0


if current_sum < 0:
current_sum = 0

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]
]

# Run test cases


for nums in test_cases:
solution = Solution()
result = [Link](nums)
print(f"nums : {nums} => max sub-array: {result}")
class :
def ( , ):
= ('inf')
= 0

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

for price in prices:


min_price = min(min_price,price)
max_profit = max(max_profit,price-min_price)
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]
]

# Run test cases


for prices in test_cases:
solution = Solution()
result = [Link](prices)
print(f"prices : {prices} => max profit: {result}")

class :
def ( , : ) -> :
= ( )
= {} # Stores the last index where each character was
seen
= 0 # Left pointer of the window
= 0 # Length of the longest substring found

for in ( ): # j is the right pointer of the window


if [ ] in :
= ( [ [ ]] + 1, ) # Move left pointer only
forward
= ( , - + 1) # Update max length
[ [ ]] = # Update the latest index of
s[j]
( [ ], )
return

= {}
= 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

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_length = max(max_length, right - left + 1)

return max_length

test_cases = [
"abcabcbb",
"bbbbb",
"pwwkew"
]

# Run test cases


for test in test_cases:
solution = Solution()
result = [Link](test)
print(f"String : {test} => lengthOfLongestSubstring: {result}")

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)

# 9. After checking all characters, return the maximum length found


return max_length

test_cases = [
"abcabcbb",
"bbbbb",
"pwwkew"
]

# Run test cases


for test in test_cases:
solution = Solution()
result = [Link](test)
print(f"String : {test} => lengthOfLongestSubstring: {result}")

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

# 4. The 'right' pointer moves from the beginning to the end of


the string
for in ( ( )):
# 5. Check if the character at the 'right' pointer is already
in our current window (char_set)
while [ ] in :
# 6. If it is, we need to shrink the window from the left
. ( [ ]) # Remove the character at the
'left' pointer from our set
+= 1 # Move the 'left' pointer one
step to the right

# 7. Add the current character (at 'right' pointer) to our


window's set
. ( [ ])
# 8. Calculate the current window's length and update
max_length if this window is longer
= ( , - + 1)

# 9. After checking all characters, return the maximum length


found
return
for in :
= ()
= . ( )
(f"String : { } => lengthOfLongestSubstring: { }")

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"
]

# Run test cases


for test in test_cases:
solution = Solution()
result = [Link](test)
print(f"String : {test} => lengthOfLongestSubstring: {result}")

= [-2, 0, 3, -5, 2, -1]


(0, 2) = -2 + 0 + 3 = 1

[ ] = [0] + [1] + ... + [ - 1]

( , ) = [ + 1] - [ ]

= [-2, 0, 3, -5, 2, -1]

= [0] # to handle sum from index 0


(2, 5) = [6] - [2]
= -3 - (-2) = -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)

def sumRange(self, left, right):


return self.prefix_sum[right + 1] - self.prefix_sum[left]
= [1, 1, 1], = 2

= [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

for num in nums:


prefix_sum += num
if (prefix_sum - k) in prefix_map:
count += prefix_map[prefix_sum - k]
prefix_map[prefix_sum] = prefix_map.get(prefix_sum, 0) + 1

return count
test_cases = [
([1,1,1], 2),
([1,2,3], 3)
]

# Run test cases


for nums, k in test_cases:
solution = Solution()
result = [Link](nums, k)
print(f"input : {nums, k} => subarraySum: {result}")

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

for num in nums:


current_sum += num
if current_sum - k in prefix_sum:
count += prefix_sum[current_sum - k]
prefix_sum[current_sum] += 1

return count

test_cases = [
([1,1,1], 2),
([1,2,3], 3)
]

# Run test cases


for nums, k in test_cases:
solution = Solution()
result = [Link](nums, k)
print(f"input : {nums, k} => subarraySum: {result}")
def ( , : [ ], : ) -> [ ]:

def ():
, = 0, ( ) - 1
= -1
while <= :
= ( + ) // 2
if [ ] < :
= + 1
else:
if [ ] == :
=
= - 1
return
def ():
, = 0, ( ) - 1
= -1
while <= :
= ( + ) // 2
if [ ] > :
= - 1
else:
if [ ] == :
=
= + 1
return

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)
]

# Run test cases


for nums, target in test_cases:
solution = Solution()
result = [Link](nums, target)
print(f"Search : {nums, target} => output: {result}")
= [[1,3],[2,6],[8,10],[15,18]]

= []
[[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

# Find First and Last Position of Element in Sorted Array


class Solution:
def searchRange(self, nums, target):
def findLeft():
left, right = 0, len(nums) - 1
index = -1
while left <= right:
mid = (left + right) // 2
if nums[mid] < target:
left = mid + 1
else:
if nums[mid] == target:
index = mid
right = mid - 1
return index

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

return [findLeft(), findRight()]

test_cases = [
([5,7,7,8,8,10],8),
([5,7,7,8,8,10],6),
([],0)
]

# Run test cases


for nums, target in test_cases:
solution = Solution()
result = [Link](nums, target)
print(f"Search : {nums, target} => output: {result}")

class Solution:
def merge(self, intervals):
# Step 1: Sort intervals by start time
[Link](key=lambda x: x[0])
merged = []

for interval in intervals:


# If merged is empty or no overlap, add it
if not merged or merged[-1][1] < interval[0]:
[Link](interval)
else:
# Overlap: merge by updating the end time
merged[-1][1] = max(merged[-1][1], interval[1])

return merged

test_cases = [
[[1,3],[2,6],[8,10],[15,18]],
[[1,4],[4,5]]
]

# Run test cases


for intervals in test_cases:
solution = Solution()
result = [Link](intervals)
print(f"Intervals : {intervals} => output: {result}")

= [-1, 0, 1, 2, -1, -4]

[-4, -1, -1, 0, 1, 2]


[[-1, -1, 2], [-1, 0, 1]]

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):
[Link]()
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:
[Link]([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]
]

# Run test cases


for nums in test_cases:
solution = Solution()
result = [Link](nums)
print(f"Nums : {nums} => output: {result}")

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:
[Link](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]
]

# Run test cases


for nums in test_cases:
solution = Solution()
result = [Link](nums)
print(f"Nums : {nums} => output: {result}")
class :
def ( , : [ ]) -> :
= 0
= ( ) - 1
= 0

while < :
= ( [ ], [ ])
= -
= ( , * )

# Move the pointer with the shorter height


if [ ] < [ ]:
+= 1
else:
-= 1

return

= [1,8,6,2,5,4,8,3,7]

# Container With Most Water


class Solution:
def maxArea(self, height):
left = 0
right = len(height) - 1
max_area = 0

while left < right:


h = min(height[left], height[right])
w = right - left
max_area = max(max_area, h * w)

# Move the pointer with the shorter height


if height[left] < height[right]:
left += 1
else:
right -= 1

return max_area

test_cases = [
[1,8,6,2,5,4,8,3,7],
[1,1]
]

# Run test cases


for height in test_cases:
solution = Solution()
result = [Link](height)
print(f"Height : {height} => output: {result}")

class Solution:
def maxArea(self, height):
left = 0
right = len(height) - 1
max_area = 0

while left < right:


new_area = (right - left) * min(height[left],height[right])
max_area = max(max_area, new_area)
if height[left] < height[right]:
left += 1
else:
right -= 1

return max_area

test_cases = [
[1,8,6,2,5,4,8,3,7],
[1,1]
]

# Run test cases


for height in test_cases:
solution = Solution()
result = [Link](height)
print(f"Height : {height} => output: {result}")

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]

# Count sort variant (2-pass)


def ( ):
= [0, 0, 0]
for in :
[ ] += 1

= 0
for in (3):
for in ( [ ]):
[ ] =
+= 1

class Solution:
def sortColors(self, nums):
low, mid, high = 0, 0, len(nums) - 1

while mid <= high:


if nums[mid] == 0:
nums[low], nums[mid] = nums[mid], nums[low]
low += 1
mid += 1
elif nums[mid] == 1:
mid += 1
else: # nums[mid] == 2
nums[mid], nums[high] = nums[high], nums[mid]
high -= 1

return nums

test_cases = [
[2,0,2,1,1,0],
[2,0,1]
]

# Run test cases


for nums in test_cases:
solution = Solution()
result = [Link](nums)
print(f"Nums : {nums} => output: {result}")

= [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]
]

# Run test cases


for nums in test_cases:
solution = Solution()
result = [Link](nums)
print(f"Nums : {nums} => output: {result}")

class Solution:
def isAnagram(self, s, t) -> bool:
return sorted(s) == sorted(t)

test_cases = [
("anagram","nagaram"),
("rat","cat")
]

# Run test cases


for s, t in test_cases:
solution = Solution()
result = [Link](s, t)
print(f"String : {s,t} => output: {result}")

from collections import Counter

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 ( ) == ( )

from collections import Counter

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

from collections import Counter

class Solution:
def canConstruct(self, ransomNote, magazine):
ransom_count = Counter(ransomNote)
magazine_count = Counter(magazine)

for char in ransom_count:


if ransom_count[char] > magazine_count.get(char, 0):
return False
return True

test_cases = [
("a","b"),
("aa","ab"),
("aa","aab")
]

# Run test cases


for s, t in test_cases:
solution = Solution()
result = [Link](s, t)
print(f"String : {s,t} => output: {result}")

class Solution:
def canConstruct(self, ransomNote: str, magazine: str) -> bool:
for char in ransomNote:
if char in magazine:
magazine="".join([Link](char,1))
else:
return False
return True

test_cases = [
("a","b"),
("aa","ab"),
("aa","aab")
]

# Run test cases


for s, t in test_cases:
solution = Solution()
result = [Link](s, t)
print(f"String : {s,t} => output: {result}")
= "A man, a plan, a canal: Panama"

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([Link]() for char in s if [Link]())
return clean_s == clean_s[::-1]

test_cases = [
"A man, a plan, a canal: Panama",
"race a car",
" "
]

# Run test cases


for s in test_cases:
solution = Solution()
result = [Link](s)
print(f"String : {s} => output: {result}")
class :
def ( , : ) -> :
def ( : , : ) -> :
while >= 0 and < ( ) and [ ] == [ ]:
-= 1
+= 1
return [ + 1: ]

= ""
for in ( ( )):
# Odd length palindrome
= ( , )
if ( ) > ( ):
=

# Even length palindrome


= ( , + 1)
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

# Even length palindrome


even_pal = expand_around_center(i, i + 1)
if len(even_pal) > len(longest):
longest = even_pal

return longest

test_cases = [
"babad",
"cbbd",
" "
]

# Run test cases


for s in test_cases:
solution = Solution()
result = [Link](s)
print(f"String : {s} => output: {result}")

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",
" "
]

# Run test cases


for s in test_cases:
solution = Solution()
result = [Link](s)
print(f"String : {s} => output: {result}")

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

print("All test cases passed!")

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

print("All test cases passed!")

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

for i in range(2, int(n**0.5) + 1):


if is_prime[i]:
for j in range(i * i, n + 1, i):
is_prime[j] = False

for i in range(2, n + 1):


if is_prime[i]:
[Link](i)

return primes

def get_primes(n):
if n < 2:
return []

primes = [2] # 2 is the first prime

# We only check odd numbers: 3, 5, 7, ..., n


# So we need to mark which odd numbers are prime
size = (n - 1) // 2 # This gives us count of odd numbers up to n
is_prime = [True] * size # True means "this odd number is prime"

for i in range(int(n**0.5) // 2):


if is_prime[i]:
prime = 2 * i + 3 # Convert index back to actual number
# Mark all multiples of prime as not prime
for j in range((prime * prime - 3) // 2, size, prime):
is_prime[j] = False

# Convert True values back to actual prime numbers


for i in range(size):
if is_prime[i]:
[Link](2 * i + 3)

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

# Step 3: Use the sieve algorithm


while p * p <= n:
# If is_prime[p] is True, then it is a prime
if is_prime[p]:
# Update all multiples of p as non-prime
for i in range(p * p, n + 1, p):
is_prime[i] = False
p += 1
return [p for p in range(n + 1) if is_prime[p]]
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 fast_modular_exponentiation(base, exponent, modulus):


result = 1
base = base % modulus # Update base if it is more than or equal to modulus
while exponent > 0:
# If exponent is odd, multiply base with result
if (exponent % 2) == 1:
result = (result * base) % modulus
# exponent must be even now
exponent = exponent >> 1 # Divide exponent by 2
base = (base * base) % modulus # Square the base
return result

# Test the function with a few examples


print(fast_modular_exponentiation(2, 10, 1000)) # Output: 24

from collections import defaultdict

def find_shared_remainder(numbers, divisor=10):


# Dictionary to store remainders
remainder_count = defaultdict(int)

# Iterate over each number and compute remainder


for number in numbers:
remainder = number % divisor
remainder_count[remainder] += 1
# If any remainder has more than one occurrence, we found a match
if remainder_count[remainder] > 1:
return f"At least two numbers have the same remainder {remainder} when divided by
return "All remainders are unique"

# Test with a list of 11 numbers


numbers = [14, 23, 32, 41, 55, 67, 78, 89, 90, 102, 110] # Remainder 4 appears twice
print(find_shared_remainder(numbers))
# Expected output: At least two numbers have the same remainder 4 when divided by 10

def max_subarray_sum(arr):
"""Return the maximum sum of a contiguous subarray."""
max_sum = float('-inf')
current_sum = 0

for num in arr:


current_sum += num
if current_sum > max_sum:
max_sum = current_sum
if current_sum < 0:
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

for num in arr:


current_sum += num
if current_sum < min_sum:
min_sum = current_sum
if current_sum > 0:
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)

for i in range(1, n + 1):


partial_sums[i] = partial_sums[i - 1] + arr[i - 1]

max_sum = float('-inf')
min_partial_sum = float('inf')

for i in range(1, n + 1):


if partial_sums[i] - min_partial_sum > max_sum:
max_sum = partial_sums[i] - min_partial_sum
if partial_sums[i] < min_partial_sum:
min_partial_sum = partial_sums[i]

return max_sum, min_partial_sum

# Test the function with a few examples


print(max_sum_subarray_partial_sums([-2,1,-3,4,-1,2,1,-5,4])) # Output: 6 (subarray [4,-1,2,
print(max_sum_subarray_partial_sums([2,-1,3,-4,5,-2])) # Output: 5 (subarray [5])
print(max_sum_subarray_partial_sums([-1,-2,-3,-4])) # Output: -1 (subarray [-1])

#stopHere
def has_binary_alternating_subseq(arr):
if arr is None or len(arr) == 0:
return False

max_length = 0
i = 0

while i < len(arr) - 1:


if arr[i] in (0, 1) and arr[i+1] in (0, 1) and arr[i] != arr[i+1]:
count = 2
current = arr[i+1]
j = i + 2
while j < len(arr) and arr[j] in (0, 1) and arr[j] != current:
count += 1
current = arr[j]
j += 1
max_length = max(max_length, count)
i = j - 1
else:
i += 1

# Handle single 0 or 1 when no longer subsequence was found


if max_length == 0 and len(arr) == 1 and arr[0] in (0, 1):
return 1

return max_length if max_length >= 1 else False


print(has_binary_alternating_subseq([0, 1, 0, 1])) # 4
print(has_binary_alternating_subseq([0, 0, 1, 1])) # False
print(has_binary_alternating_subseq([1, 0, 1, 0, 0, 1])) # 4
print(has_binary_alternating_subseq([1, 1, 1])) # False

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([Link](smallest))

return new_arr
solution = selection_sort(arr)
print(solution)

arr = [20, 15, 3, 5, 10, 19, 23, 30, 100]

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([Link](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:])

arr = [20, 15, 3, 5, 10, 19, 23, 30, 100]


solution = count_items(arr)
print(solution) # Output: 9

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:

def binary_search(arr, target, low, high):


if low > high:
return -1 # Base case: target not found

mid = (low + high) // 2

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 merge(left_half, right_half)

def merge(left, right):


result = []
i = j = 0

# Merge the two sorted halves


while i < len(left) and j < len(right):
if left[i] <= right[j]:
[Link](left[i])
i += 1
else:
[Link](right[j])
j += 1

# Append remaining elements


[Link](left[i:])
[Link](right[j:])

return result

# Example usage:
arr = [10, 5, 2, 3]
print(merge_sort(arr)) # Output: [2, 3, 5, 10]

def stack_composer(arr1, arr2):


menu = {}
for fruit in fruits:
for price in prices:
menu[fruit] = price

return menu

fruits = ['Apple', 'Banana', 'Water Mellon']


prices = [1.25, 1.79, 2.5]
book = stack_composer(fruits, prices)
print(book)
print(book["Water Mellon"])
for fruit, price in [Link]():
print(f"Fruit: {fruit} price is: {price}")

You might also like