Problem 1 — Collatz Steps
Difficulty: Easy
Task: Start with a positive integer n. While n != 1: if even → n/2, if odd → 3n+1. Count how many times the rule was applied.
- Input:
n - Output: number of steps (0 if
n = 1) - Constraints:
1 ≤ n ≤ 10^6 - Example:
6 → 3 → 10 → 5 → 16 → 8 → 4 → 2 → 1= 8 steps
| Input | Output |
|---|---|
| 6 | 8 |
| 1 | 0 |
| 27 | 111 |
My Answer
n = int(input())
def main(n,ans=""):
ans=ans+ " "+str(n)
if n==1:
return ans
elif n%2==0:
return main(n//2,ans)
else:
return main(3*n+1,ans)
answer=main(n,"")
x=answer.split()
answer=len(x)
print(answer)Problem 2 — Sum of the Valid Numbers
Difficulty: Easy
Task: A line has space-separated tokens. A token is valid if int(token) accepts it (12, -3, +5). Print the sum of valid integers and the count of invalid tokens. Use try/except.
- Input: one line of tokens (1–100 tokens, each ≤ 10 chars)
- Output:
sum bad_count - Example:
10 abc 5 3.5 -2 x1→13 3
| Input | Output |
|---|---|
10 abc 5 3.5 -2 x1 | 13 3 |
- -- 4-2 +5 | 5 3 |
hello world | 0 2 |
My Answer
tokens = input().split()
total=0
bad=0
for i in tokens:
try:
total+=int(i)
except:
bad+=1
print(total, bad)Problem 3 — Recursive Palindrome
Difficulty: Easy
Task: Complete recursive is_pal(s) returning True if s is a palindrome. No loops – must call itself on a shorter string.
- Input: string
s(1 ≤ |s| ≤ 500, lowercase) - Output:
True/False - Idea: first == last, and the middle is a palindrome
| Input | Output |
|---|---|
| racecar | True |
| ab | False |
| a | True |
My Answer
def is_pal(s):
if len(s)<=1:
return True
if s[0]==s[-1]:
return is_pal(s[1:-1])
else:
return False
s = input()
answer = is_pal(s)
print(answer)Problem 4 — Versions of a List
Difficulty: Medium
Task: A list of n ints is changed m times. Each change i v sets item at position i to v. Record every version (version 0 = original) and print all m+1 versions.
- Input:
n, thennints, thenm, thenmlines ofi v - Output:
m+1lines, one per version - Constraints:
n, m ≤ 20, values in[-100, 100] - Starter: store versions in list
answer(each a list of ints)
Sample:
3
1 2 3
2
0 9
2 7
Output:
1 2 3
9 2 3
9 2 7
My Answer
n = int(input())
nums = list(map(int, input().split()))
m = int(input())
changes = []
for _ in range(m):
i, v = map(int, input().split())
changes.append((i, v))
answer=[nums[:]]
for i in changes:
nums[i[0]]=i[1]
b=nums[:]
answer.append(b)
for version in answer:
print(*version) # prints list entries without bracketsProblem 5 — Count in a Sorted List
Difficulty: Medium
Task: Sorted list (non-decreasing, duplicates allowed) of n ints; for each of q queries x print how many times x appears. Use binary search for start and end of x.
- Input:
n, sorted list,q, query values - Output:
qlines of counts - Constraints:
n, q ≤ 10^5, values in[-10^9, 10^9] - Starter: store counts in list
answer
Sample: list 1 2 2 2 5 9, queries 2 3 1 9 0 10 → 3 0 1 1 0 0 (one per line)
My Answer
n = int(input())
a = list(map(int, input().split()))
q = int(input())
queries = list(map(int, input().split()))
def find_low(l, target):
low, high = 0, len(l)
while low < high:
mid = (low + high) // 2
if l[mid] < target:
low = mid + 1
else:
high = mid
return low
def find_high(l, target):
low, high = 0, len(l)
while low < high:
mid = (low + high) // 2
if l[mid] <= target:
low = mid + 1
else:
high = mid
return low
answer=[]
for i in queries:
x= find_high(a,i)-find_low(a,i)
answer.append(x)
for c in answer:
print(c)Problem 6 — Stairs with Broken Steps
Difficulty: Medium
Task: Staircase with n steps. Start at 0, move 1 or 2 steps at a time, never land on a broken step. Count ways to reach step n. Use memoisation (remember answers).
- Input:
n k, thenkbroken step numbers (empty line ifk = 0) - Output: number of ways (0 if step
nis broken) - Constraints:
n ≤ 50 - Starter: store result in
answer
| Input | Output |
|---|---|
5 1 / 3 | 2 |
10 3 / 2 5 8 | 1 |
4 2 / 1 2 | 0 |
My Answer
n, k = map(int, input().split())
broken = list(map(int, input().split()))
def ways(n):
if n<=0:
return 0
if n==1:
return 1
if n==2:
return 2
return ways(n-1)+ways(n-2)
low=0
waylist=[]
for i in broken:
waylist.append((i-1)-low)
low=i+1
if low<n:
waylist.append(n-low)
elif low>n:
answer*=0
answer=1
for i in waylist:
answer*=ways(i)
print(answer)Problem 7 — Best Block Sum
Difficulty: Medium
Task: Find the largest sum of a block (≥ 1 consecutive items) in a list that may have negatives. Single pass: track best sum of a block ending at the current position.
- Input:
n, thennints - Output: largest block sum
- Constraints:
n ≤ 10^5, values in[-1000, 1000] - Starter: store result in
answer
| Input | Output |
|---|---|
2 -5 4 -1 3 -6 2 | 6 |
-3 -1 -2 | -1 |
1 2 3 -10 4 5 | 9 |
My Answer
n = int(input())
a = list(map(int, input().split()))
low=0
high=n-1
sum_high=0
sum=0
for i in range(n):
sum+=a[i]
if sum>sum_high:
sum_high=sum
high=i
print("sum=",sum,"sumhigh=",sum_high)
print(high)
sum=sum_high
for i in range(high):
sum-=a[i]
if sum>sum_high:
sum_high=sum
print("sum=",sum,"sumhigh=",sum_high)
print(sum_high)Problem 8 — Subsets with a Given Sum
Difficulty: Hard
Task: Given n distinct positive ints and target T, find every subset summing to T. Each subset in increasing order; subsets in dictionary order (shorter prefix first). Use backtracking (add → recurse → remove). Print -1 if none.
- Input:
n, thenints,T - Output: one subset per line, or
-1 - Constraints:
n ≤ 15, values 1–100,T ≤ 200 - Starter: subsets stored in list
answer
Sample: 2 3 5 7, T = 10 → 2 3 5 and 3 7
My Answer
n = int(input())
nums = list(map(int, input().split()))
target = int(input())
def backtrack(nums, path, index, sum=0):
if sum==target:
answer.append(path[:])
for i in range(index, len(nums)):
path.append(nums[i]) # add an element
sum+=nums[i]
# print(path,"sum=",sum)
backtrack(nums, path, i+1,sum) # recursive call
path.pop()
sum-=nums[i] # remove element
answer=[]
backtrack(nums, [], 0)
if len(answer) == 0:
print(-1)
for subset in answer:
print(*subset) # prints list entries without bracketsProblem 9 — Queens on a Board
Difficulty: Hard
Task: Count the ways to place n non-attacking queens on an n × n board. Place one row at a time, backtrack when stuck.
- Input:
n(1 ≤ n ≤ 9) - Output: number of ways
- Starter: store result in
answer
| Input | Output |
|---|---|
| 4 | 2 |
| 6 | 4 |
| 8 | 92 |
My Answer
#generateing all permutations of n:
n = int(input())
def backtrack(path, used):
# Base case: all n numbers are placed
if len(path) == n:
permutations.append(path[:]) # Save a copy, not a reference!
return
for num in range(1, n + 1):
if not used[num]:
used[num] = True
path.append(num)
backtrack(path, used)
path.pop()
used[num] = False
permutations = []
print(permutations)
used = [False] * (n+1) # 1-indexed boolean array for numbers 1..n
backtrack([], used)
answer=0
for i in permutations:
diagpos={}
diagneg={}
for j in range (n):
x=j-i[j]
y=j+i[j]
diagpos[x]=0
diagneg[y]=0
if len(diagpos)==n and len(diagneg)==n:
answer+=1
print(i)
print(answer)
Problem 10 — The k-th Move of the Tower of Hanoi
Difficulty: Hard
Task: 3 pegs A, B, C; n disks (1 = smallest) start on A, goal is C. Standard method: move m-1 disks X→Z, disk m X→Y, m-1 disks Z→Y (total 2^n - 1 moves). Print the k-th move without generating the others.
- Input:
n k - Output:
disk src dst - Constraints:
n ≤ 60,1 ≤ k ≤ 2^n - 1 - Starter: variables
disk,src,dst
| Input | Output |
|---|---|
3 4 | 3 A C |
5 10 | 2 C A |
60 576460752303423488 | 60 A C |
My Answer
Filled in by Claude Your
q10.pywas empty in the upload, so this solution is mine, not yours.
n, k = map(int, input().split())
def solve(n, k, X, Y, Z):
# k-th move of moving n disks from X to Y using Z
half = 2 ** (n - 1)
if k == half:
return n, X, Y
if k < half:
return solve(n - 1, k, X, Z, Y)
return solve(n - 1, k - half, Z, Y, X)
disk, src, dst = solve(n, k, 'A', 'C', 'B')
print(disk, src, dst)Problem 11 — Recursive Star Pattern
Difficulty: Medium
Task: Complete recursive pattern(n, indent) (fill 4 blanks) that prints a symmetric star pattern. No loops or extra functions; string multiplication allowed. n = 0 prints nothing. Don’t print spaces between stars or extra blank lines.
def pattern(n, indent=0):
if n == 0:
____________________ # Blank 1
____________________ # Blank 2
print(____________________) # Blank 3
____________________ # Blank 4- Input:
n(1 ≤ n ≤ 8)
Output for n = 3:
*
***
*****
***
*
(for n=2: *, ***, *; for n=1: *)
My Answer
def pattern(n, indent=0):
if n == 0:
return
pattern(n-1,indent+2)
print(indent*" ","*"*(2*n-1))
pattern(n-1,indent+2)
n = int(input())
pattern(n)Problem 12 — In-Place Partitioning
Difficulty: Medium
Task: Complete partition(L, x) so all ints <= x come before all ints > x, in place, and return the count of elements <= x.
- Restrictions: modify
Litself; only O(1) extra variables; no new list/collection, no copy/slice, no recursion, nosort()/sorted(). SwappingL[i], L[j] = L[j], L[i]is allowed. - Input: line 1 distinct ints (
L), line 2x - Constraints:
n ≤ 10^5, values in[-10^9, 10^9] - Don’t modify driver code. Order within each group doesn’t matter.
| Input | Output |
|---|---|
8 3 7 1 6 2 / 3 | 3 / True |
4 9 6 / 2 | 0 / True |
-3 5 0 2 / 5 | 4 / True |
My Answer
Filled in by Claude Your
q12.pywas empty in the upload, so this solution is mine, not yours.
def partition(L, x):
i = 0 # everything before i is <= x
for j in range(len(L)):
if L[j] <= x:
L[i], L[j] = L[j], L[i]
i += 1
return i
L = list(map(int, input().split()))
x = int(input())
# The copy below is used only to check your answer.
# You must not create a copy inside partition().
original = L.copy()
k = partition(L, x)
print(k)
valid = (
type(k) is int
and 0 <= k <= len(L)
and sorted(L) == sorted(original)
and all(L[i] <= x for i in range(k))
and all(L[i] > x for i in range(k, len(L)))
)
print(valid)Problem 13 — Merging Two Sorted Lists
Difficulty: Medium
Task: Complete merge(A, B) returning a new sorted list of all elements of two sorted lists. Keep duplicates, don’t modify A/B, no sort()/sorted().
- Input: line 1 =
A, line 2 =B(empty line = empty list) - Output: merged list printed as a Python list
- Constraints: sizes ≤ 10^5, values in
[-10^9, 10^9]
| A | B | Output |
|---|---|---|
1 4 7 | 2 4 8 | [1, 2, 4, 4, 7, 8] |
-5 -1 3 | -4 0 2 9 | [-5, -4, -1, 0, 2, 3, 9] |
1 1 5 | 1 2 2 | [1, 1, 1, 2, 2, 5] |
My Answer
def merge(A, B):
list_sort=[]
i=0
j=0
n=len(A)
m=len(B)
while i<=n and j<=m:
if i==n:
list_sort.extend(B[j:])
break
elif j==m:
list_sort.extend(A[i:])
break
elif A[i]<=B[j]:
list_sort.append(A[i])
i+=1
else:
list_sort.append(B[j])
j+=1
return list_sort
pass
A = list(map(int, input().split()))
B = list(map(int, input().split()))
answer = merge(A, B)
print(answer)Problem 14 — Strongest Stock Price Rally
Difficulty: Medium
Task: Complete strongest_rally(prices) returning the largest prices[j] - prices[i] with i < j; return 0 if no positive rally. Only O(1) extra variables; don’t modify input, no extra collections, no sorting.
- Input: one line of space-separated prices
- Output: one integer
- Constraints:
n ≤ 10^5, prices in[1, 10^9]
| Input | Output |
|---|---|
120 100 115 90 130 125 | 40 |
150 100 120 | 20 |
100 90 80 70 | 0 |
75 | 0 |
My Answer
Filled in by Claude Your
q14.pywas empty in the upload, so this solution is mine, not yours.
def strongest_rally(prices):
best = 0
lowest = prices[0]
for p in prices[1:]:
if p - lowest > best:
best = p - lowest
if p < lowest:
lowest = p
return best
prices = list(map(int, input().split()))
answer = strongest_rally(prices)
print(answer)Problem 15 — Distinct Permutations
Difficulty: Hard
Task: Complete recursive permutations(L, i) printing all distinct permutations of a list that may contain repeats. i = position being filled; initial call permutations(L, 0). Backtrack (choose → recurse → undo). Print with print(L) when full.
- May use loops and a local
setper call to skip repeated values at a position. - No
itertools.permutations, no storing all results to dedupe afterwards. Lmust be restored to original order at the end.- Input: one line of ints (
|L| ≤ 8, values in[-9, 9]) - Output: each distinct permutation as a Python list, any order
Sample: 1 1 2 → [1, 1, 2], [1, 2, 1], [2, 1, 1]
My Answer
def backtrack(path, used,n):
# Base case: all n numbers are placed
if len(path) == len(n):
permutations.append(path[:]) # Save a copy, not a reference!
return
for num in range(len(n)):
if n[num]==n[num-1]:
continue
if not used[num]:
used[num] = True
path.append(num)
backtrack(path, used,n)
path.pop()
used[num] = False
permutations = []
n=[1,1,1,2,3,4]
used=[False]*len(n)
backtrack([],used,n)
for i in permutations:
print(*i)Problem 16 — Integer Logarithm
Difficulty: Easy to Medium
Task: Complete recursive integer_log(n) returning ⌊log₂ n⌋ (largest k with 2^k ≤ n).
- Not allowed: loops, log functions, floats,
bit_length(), binary conversion.//is allowed. - Input:
n(1 ≤ n ≤ 10
| Input | Output |
|---|---|
| 20 | 4 |
| 32 | 5 |
| 1 | 0 |
My Answer
Filled in by Claude Your
q16.pywas empty in the upload, so this solution is mine, not yours.
def integer_log(n):
if n <= 1:
return 0
return 1 + integer_log(n // 2)
n = int(input())
answer = integer_log(n)
print(answer)Problem 17 — Counting Ones in Binary
Difficulty: Easy to Medium
Task: Complete recursive count_ones(n) returning the number of 1s in the binary representation of n.
- Not allowed: loops,
bin(),bit_count(), bitwise operators, strings.//and%are allowed. - Input:
n(0 ≤ n ≤ 10
| Input | Output |
|---|---|
| 13 | 3 |
| 8 | 1 |
| 0 | 0 |
My Answer
Filled in by Claude Your
q17.pywas empty in the upload, so this solution is mine, not yours.
def count_ones(n):
if n == 0:
return 0
return n % 2 + count_ones(n // 2)
n = int(input())
answer = count_ones(n)
print(answer)Problem 18 — Lab Slots for Students
Difficulty: Medium to Hard
Task: Count the ways to divide n students into k lab slots so every slot has ≥ 1 student. Complete recursive ways(n, k).
- Example:
ways(3, 2) = 3→([1],[2,3]),([1,2],[3]),([1,3],[2]) - Hint: for the n-th student: (1) joins any of
kexisting non-empty slots, or (2) goes into the one empty slot (so firstn-1students filledk-1slots).
def ways(n, k):
# Write your recursive code here
pass
n = int(input("Enter n: "))
k = int(input("Enter k: "))
print(ways(n, k))My Answer
Filled in by Claude Your
q18.pywas empty in the upload, so this solution is mine, not yours.
def ways(n, k):
if k <= 0 or n < k:
return 0
if n == k:
return 1
# n-th student joins one of k existing slots, or fills the empty slot
return k * ways(n - 1, k) + ways(n - 1, k - 1)
n = int(input("Enter n: "))
k = int(input("Enter k: "))
print(ways(n, k))Problem 19 — Seating Arrangement for Students
Difficulty: Medium to Hard
Task: n people in a line; choose exactly k with no two adjacent. Count the ways. Complete recursive ways(n, k) (assume n, k >= 1).
- Example:
ways(4, 2) = 3→[1,3],[1,4],[2,4] - Hint: look at person
n: (1) not chosen → choosekfrom firstn-1; (2) chosen → personn-1can’t be, so choosek-1from firstn-2.
def ways(n, k):
# Write your recursive code here
pass
n = int(input("Enter n: "))
k = int(input("Enter k: "))
print(ways(n, k))My Answer
Filled in by Claude Your
q19.pywas empty in the upload, so this solution is mine, not yours.
# assume n, k >= 1
def ways(n, k):
if k == 0:
return 1
if n <= 0:
return 0
# person n not chosen + person n chosen (so n-1 is skipped)
return ways(n - 1, k) + ways(n - 2, k - 1)
n = int(input("Enter n: "))
k = int(input("Enter k: "))
print(ways(n, k))Problem 20 — Power of a Matrix
Difficulty: Medium to Hard
Task: Implement three functions for an n × n matrix M:
row_col_prod(A, B, i, j)– dot product of rowiofAwith columnjofB.mat_mul(A, B)– returnA × Bas a new matrix, usingrow_col_prod. Don’t modifyAorB.mat_pow(M, k)– returnM^k(k ≥ 0,M^0 = I). Must be recursive. Don’t modifyM;k = 1must return a fresh copy (no aliasing).
Tests to pass:
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
row_col_prod(A, B, 0, 0) == 19
row_col_prod(A, B, 0, 1) == 22
row_col_prod(A, B, 1, 0) == 43
row_col_prod(A, B, 1, 1) == 50
mat_mul(A, B) == [[19, 22], [43, 50]] # A and B unchanged
F = [[1, 1], [1, 0]]
mat_pow(F, 5) == [[8, 5], [5, 3]]
mat_pow(A, 0) == [[1, 0], [0, 1]]
Q = mat_pow(A, 1)
A == Q and id(A) != id(Q)My Answer
def row_col_prod(A, B, i, j):
sum=0
for t in range(len(A[1])):
sum+= A[i][t]*B[t][j]
return sum
def mat_mul(A, B):
mat=[]
for i in range(len(B)):
row=[]
for j in range(len(A[1])):
row.append(row_col_prod(A,B,i,j))
mat.append(row)
return mat
def mat_pow(M, k):
X=M
for i in range(k-1):
X= mat_mul(X, M)
return X
A = [[1, 2], [3, 4]]
B = [[5, 6], [7, 8]]
# row_col_prod
print(row_col_prod(A, B, 0, 0) == 19 )# 1*5 + 2*7, True
print((row_col_prod(A, B, 0, 1) == 32 ))# 1*6 + 2*8, True
print(row_col_prod(A, B, 1, 0) == 43) # 3*5 + 4*7, True
row_col_prod(A, B, 1, 1) == 50 # 3*6 + 4*8, True
F = [[1, 1], [1, 0]]
mat_pow(F, 5) == [[8, 5], [5, 3]] # True
mat_pow(A, 0) == [[1, 0], [0, 1]] # identity, True
Q = mat_pow(A, 1)
print(A == Q) # True
print(id(F) != id(Q)) # TrueProblem 21 — Grid Paths with Obstacles
Difficulty: Medium
Task: m × n grid, start top-left, reach bottom-right, moving only right or down. Cells with 1 are obstacles, 0 are free. Count valid paths. Complete count_paths(grid, i, j).
- Input:
m n, thenmrows ofnints (0/1) - Output: number of paths
- Constraints:
1 ≤ m, n ≤ 10
| Grid | Output |
|---|---|
0 0 0 / 0 1 0 / 0 0 0 | 2 |
0 0 / 0 0 | 2 |
0 0 0 / 0 1 0 | 1 |
m, n = map(int, input().split())
grid = [list(map(int, input().split())) for _ in range(m)]
def count_paths(grid, i, j):
# write your code here
answer = count_paths(grid, 0, 0)
print(answer)My Answer
Filled in by Claude Your
q21.pywas empty in the upload, so this solution is mine, not yours.
m, n = map(int, input().split())
grid = [list(map(int, input().split())) for _ in range(m)]
def count_paths(grid, i, j):
if i >= m or j >= n or grid[i][j] == 1:
return 0
if i == m - 1 and j == n - 1:
return 1
return count_paths(grid, i + 1, j) + count_paths(grid, i, j + 1)
answer = count_paths(grid, 0, 0)
print(answer)Problem 22 — Combination Sum
Difficulty: Medium
Task: Given n distinct positive ints (candidates) and target T, find all unique combinations summing to T. Each candidate may be reused unlimited times. Print NONE if there’s none.
- Input:
n T, then thencandidates - Output: one combination per line
- Constraints:
n ≤ 20,T ≤ 30
| Input | Output |
|---|---|
4 7 / 2 3 6 7 | 2 2 3 and 7 |
3 5 / 2 3 5 | 2 3 and 5 |
2 1 / 2 3 | NONE |
n, T = map(int, input().split())
cands = sorted(map(int, input().split()))
res = [] # collect your answers in res
def backtrack(start, remaining, path):
# write your code here
backtrack(0, T, [])
answer = res
if not answer:
print("NONE")
else:
for combo in answer:
print(combo)My Answer
Filled in by Claude Your
q22.pywas empty in the upload, so this solution is mine, not yours.
Note: it stores each combination as a space-joined string so the output looks like
2 2 3(the starter’sprint(combo)would otherwise print[2, 2, 3]).
n, T = map(int, input().split())
cands = sorted(map(int, input().split()))
res = [] # collect your answers in res
def backtrack(start, remaining, path):
if remaining == 0:
res.append(" ".join(map(str, path))) # stored as text so it prints as "2 2 3"
return
for i in range(start, len(cands)):
if cands[i] > remaining:
break
path.append(cands[i])
backtrack(i, remaining - cands[i], path) # i, not i+1: reuse allowed
path.pop()
backtrack(0, T, [])
answer = res
if not answer:
print("NONE")
else:
for combo in answer:
print(combo)