Coding Problems - Python Array Problems
Coding Problems - Python Array Problems
Equilibrium Index
Find an index where the sum of left elements equals the sum of right elements.
Example
Input: [1, 3, 5, 2, 2]
Output: 2
Explanation:
Left sum = 1 + 3 = 4
Right sum = 2 + 2 = 4
Python Code
PythonRundef equilibrium_index(arr):
total_sum = sum(arr)
left_sum = 0
for i in range(len(arr)):
total_sum -= arr[i] # right sum
if left_sum == total_sum:
return i
left_sum += arr[i]
return -1
arr = [1, 3, 5, 2, 2]
print(equilibrium_index(arr))
Time Complexity
O(n)
2. Sort 0s, 1s, and 2s (Dutch National Flag)
Example
Input: [0, 2, 1, 2, 0, 1]
Output: [0, 0, 1, 1, 2, 2]
Python Code
PythonRundef sort_012(arr):
low = 0
mid = 0
high = len(arr) - 1
if arr[mid] == 0:
arr[low], arr[mid] = arr[mid], arr[low]
low += 1
mid += 1
elif arr[mid] == 1:
mid += 1
else:
arr[mid], arr[high] = arr[high], arr[mid]
high -= 1
return arr
arr = [0, 2, 1, 2, 0, 1]
print(sort_012(arr))
Time Complexity
O(n)
3. Majority Element
Find element appearing more than n/2 times.
Example
Input: [2, 2, 1, 2, 3, 2, 2]
Output: 2
candidate = None
count = 0
# Find candidate
for num in arr:
if count == 0:
candidate = num
if num == candidate:
count += 1
else:
count -= 1
# Verify candidate
if [Link](candidate) > len(arr) // 2:
return candidate
return -1
arr = [2, 2, 1, 2, 3, 2, 2]
print(majority_element(arr))
Time Complexity
O(n)
4. Non-Repeating Elements
Find all elements appearing exactly once.
Example
Input: [1, 2, 2, 3, 4, 4, 5]
Output: [1, 3, 5]
Python Code
PythonRundef non_repeating(arr):
freq = {}
result = []
if len(result) == 0:
return -1
return result
arr = [1, 2, 2, 3, 4, 4, 5]
print(non_repeating(arr))
Time Complexity
O(n)
5. Move Zeros to End (Zero Shifting)
Example
Input: [0, 1, 0, 3, 12]
Output: [1, 3, 12, 0, 0]
Python Code
PythonRundef move_zeros(arr):
position = 0
if arr[i] != 0:
arr[position], arr[i] = arr[i], arr[position]
position += 1
return arr
Time Complexity
O(n)
These are super common in TCS-style coding rounds because they test:
Arrays
Optimization
Hashing
Pointer logic
Problem-solving speed
Example
Input: [40, 10, 20, 30, 20]
Output: [4, 1, 2, 3, 2]
Python Code
PythonRundefreplace_by_rank(arr):
sorted_unique=sorted(set(arr))
rank= {}
foriinrange(len(sorted_unique)):
rank[sorted_unique[i]] =i+1
result= []
fornuminarr:
[Link](rank[num])
returnresult
Time Complexity
O(n log n)
Example
Input: [7, 4, 8, 2, 9]
Output: 3
Explanation:
7 → counted
8 > 7 → counted
9 > 8 → counted
Python Code
PythonRundefprior_element_count(arr):
iflen(arr) ==0:
return0
count=1
maximum=arr[0]
foriinrange(1, len(arr)):
ifarr[i] >maximum:
count+=1
maximum=arr[i]
returncount
arr= [7, 4, 8, 2, 9]
print(prior_element_count(arr))
Time Complexity
O(n)
Example
Input:
Array = [1, 2, 4, 6, 10]
Target = 8
Output: [1, 3]
Because 2 + 6 = 8
Python Code
PythonRundeftwo_sum_sorted(arr, target):
left=0
right=len(arr) -1
whileleft<right:
current_sum=arr[left] +arr[right]
ifcurrent_sum==target:
return [left, right]
elifcurrent_sum<target:
left+=1
else:
right-=1
return-1
print(two_sum_sorted(arr, target))
Time Complexity
O(n)
Python Code
PythonRundefcount_distinct(arr):
returnlen(set(arr))
arr= [1, 2, 2, 3, 4, 4, 5]
print(count_distinct(arr))
Time Complexity
O(n)
Kth Smallest
Example
Input:
Array = [7, 10, 4, 3, 20, 15]
K=3
Output: 7
Python Code
PythonRundefkth_smallest(arr, k):
[Link]()
returnarr[k-1]
print(kth_smallest(arr, k))
Kth Largest
Example
Input:
Array = [7, 10, 4, 3, 20, 15]
K=2
Output: 15
Python Code
PythonRundefkth_largest(arr, k):
[Link](reverse=True)
returnarr[k-1]
print(kth_largest(arr, k))
Time Complexity
O(n log n)
Array traversal
Sorting
Hashing
Optimization
Two-pointer logic
Example
Input:
123
456
Output:
14
25
36
Python Code
PythonRundeftranspose_matrix(matrix):
rows=len(matrix)
cols=len(matrix[0])
transpose= []
forjinrange(cols):
new_row= []
foriinrange(rows):
new_row.append(matrix[i][j])
[Link](new_row)
returntranspose
matrix= [
[1, 2, 3],
[4, 5, 6]
]
result=transpose_matrix(matrix)
forrowinresult:
print(row)
Time Complexity
O(rows × cols)
22. Row with Maximum 1s
Find row index containing maximum number of 1s.
Example
Input:
0111
0011
1111
0000
Output:
Python Code
PythonRundefrow_with_max_ones(matrix):
max_count=0
row_index=-1
foriinrange(len(matrix)):
count=matrix[i].count(1)
ifcount>max_count:
max_count=count
row_index=i
returnrow_index
matrix= [
[0, 1, 1, 1],
[0, 0, 1, 1],
[1, 1, 1, 1],
[0, 0, 0, 0]
]
print(row_with_max_ones(matrix))
Time Complexity
O(n × m)
Example
Input: [4, 3, 4, 5, 5]
Output: 3
Python Code
PythonRundefodd_occurring(arr):
result=0
fornuminarr:
result^=num
returnresult
arr= [4, 3, 4, 5, 5]
print(odd_occurring(arr))
Why XOR Works
Properties:
a^a=0
0^a=a
Time Complexity
O(n)
Starting day
Example
Input:
Output:
Logic
Sunday occurs every 7 days.
Find first Sunday position.
Python Code
PythonRundefsunday_counter(start_day, total_days):
days= [
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday",
"Sunday"
]
start_index=[Link](start_day)
count=0
fordayinrange(1, total_days+1):
current_day= (start_index+day-1) %7
ifdays[current_day] =="Sunday":
count+=1
returncount
print(sunday_counter("Monday", 30))
Time Complexity
O(n)
25. Candy JAR / Refill Simulation
A jar has:
Capacity = N
Refill Threshold = K
Customer order = M
Example
Input:
N = 10
K=5
Orders = [2, 3, 5, 4]
Simulation
Order Candies Left
Start 10
2 8
3 5
5 0 → refill to 10
4 6
Total sold = 14
Remaining = 6
Python Code
PythonRundefcandy_jar(capacity, threshold, orders):
candies=capacity
sold=0
fororderinorders:
ifcandies<order:
candies=capacity
candies-=order
sold+=order
ifcandies<threshold:
candies=capacity
returnsold, candies
capacity=10
threshold=5
orders= [2, 3, 5, 4]
Time Complexity
O(n)
TCS NQT
Infosys
Cognizant
Wipro
Capgemini
Logic building
Array/Matrix handling
Simulation thinking
XOR tricks
Traversal concepts
Majority Element
Character Frequency
Main Idea
Store:
element → count
using:
Dictionary (dict)
HashMap
Set
Basic Template
PythonRunfreq= {}
foriteminarr:
freq[item] =[Link](item, 0) +1
print(freq)
[1, 2, 2, 3, 1, 4]
Output:
{
1: 2,
2: 2,
3: 1,
4: 1
}
Python Code
PythonRunarr= [1, 2, 2, 3, 1, 4]
freq= {}
fornuminarr:
freq[num] =[Link](num, 0) +1
print(freq)
[4, 5, 1, 2, 1, 4]
Output:
Python Code
PythonRundeffirst_non_repeating(arr):
freq= {}
fornuminarr:
freq[num] =[Link](num, 0) +1
fornuminarr:
iffreq[num] ==1:
returnnum
return-1
arr= [4, 5, 1, 2, 1, 4]
print(first_non_repeating(arr))
Example 3 — Count Distinct Elements
PythonRunarr= [1, 2, 2, 3, 4, 4]
print(len(set(arr)))
Important Functions
Function Meaning
dict() Create hashmap
set() Store unique elements
get(key, 0) Safe fetching
count() Frequency count
in Check existence
Time Complexity
Operation Complexity
Insert O(1)
Search O(1)
frequency
repeating
duplicate
unique
count occurrence
majority
non-repeating
➡️ Think:
HASHMAP / DICTIONARY
Two Sum
Sort 0s 1s 2s
Remove Duplicates
Move Zeros
Reverse Array
Equilibrium Problems
Main Idea
Use:
Left pointer
Right pointer
whileleft<right:
ifcondition:
left+=1
else:
right-=1
[1, 2, 4, 6, 10]
target = 8
Output:
[1, 3]
Python Code
PythonRundeftwo_sum(arr, target):
left=0
right=len(arr) -1
whileleft<right:
current=arr[left] +arr[right]
ifcurrent==target:
return [left, right]
elifcurrent<target:
left+=1
else:
right-=1
return-1
print(two_sum(arr, 8))
position=0
foriinrange(len(arr)):
ifarr[i] !=0:
arr[position], arr[i] =arr[i], arr[position]
position+=1
returnarr
print(move_zeros(arr))
left=0
right=len(arr) -1
whileleft<right:
left+=1
right-=1
returnarr
arr= [1, 2, 3, 4]
print(reverse_array(arr))
Time Complexity
Usually:
O(n)
sorted array
pair sum
reverse
move elements
partition
swap
➡️ Think:
TWO POINTER
Equilibrium Index
Maximum Guests
Subarray Sum
Main Idea
Store cumulative sums.
[2, 4, 6, 8]
Prefix Sum:
Python Code
PythonRundefprefix_sum(arr):
prefix[0] =arr[0]
foriinrange(1, len(arr)):
prefix[i] =prefix[i-1] +arr[i]
returnprefix
arr= [2, 4, 6, 8]
print(prefix_sum(arr))
Formula:
s u m ( L , R )= p r e f i x [ R ] − p r e f i x [ L − 1 ]
Example
Array:
[2, 4, 6, 8]
Result:
4 + 6 + 8 = 18
Python Code
PythonRundefrange_sum(prefix, left, right):
ifleft==0:
returnprefix[right]
returnprefix[right] -prefix[left-1]
arr= [2, 4, 6, 8]
prefix=prefix_sum(arr)
print(range_sum(prefix, 1, 3))
prefix[i - 1]
Right sum:
total_sum - prefix[i]
If equal:
cumulative
running total
subarray sum
equilibrium
range sum
➡️ Think:
PREFIX SUM
Automobile Production
Candy Jar
Fare Calculation
Triplets Equality
Ticket Billing
Salary Calculation
Main Idea
Convert:
Logical thinking
Condition handling
Edge cases
Simulation
INVALID INPUT
# Main logic
result=formula_or_simulation
returnresult
Capacity = N
Threshold = K
Orders given
Python Code
PythonRundefcandy_jar(capacity, threshold, orders):
ifcapacity<=0orthreshold<0:
return"Invalid Input"
candies=capacity
sold=0
fororderinorders:
iforder>capacity:
return"Invalid Input"
ifcandies<order:
candies=capacity
candies-=order
sold+=order
ifcandies<threshold:
candies=capacity
returnsold, candies
First 5 km → ₹10/km
After 5 km → ₹8/km
Python Code
PythonRundeffare(distance):
ifdistance<0:
return"Invalid Input"
ifdistance<=5:
returndistance*10
print(fare(8))
Example 3 — Triplets Equality
Check whether:
a² + b² = c²
Python Code
PythonRundeftriplet(a, b, c):
ifa<=0orb<=0orc<=0:
return"Invalid Input"
returna*a+b*b==c*c
print(triplet(3, 4, 5))
story
factory
vehicle
billing
candies
passengers
simulation
➡️ Think:
CONDITIONS + FORMULAS + EDGE CASES
Pattern 5 — String Traversal & Manipulation
Used in:
Palindrome
Anagram
Caesar Cipher
Compression
Missing Alphabet
Character Frequency
Reverse Words
Main Idea
Traverse characters one by one.
Use:
loops
ASCII values
frequency arrays
string building
Example 1 — Palindrome
Input:
madam
Output:
True
Python Code
PythonRundefpalindrome(s):
returns==s[::-1]
print(palindrome("madam"))
Example 2 — Anagram
Input:
listen
silent
Output:
True
Python Code
PythonRundefanagram(s1, s2):
returnsorted(s1) ==sorted(s2)
print(anagram("listen", "silent"))
Python Code
PythonRundefcaesar_cipher(text, shift):
result=""
forchintext:
[Link]():
result+=new_char
else:
result+=ch
returnresult
print(caesar_cipher("ABC", 2))
Example 4 — Character Frequency
PythonRundeffrequency(s):
freq= {}
forchins:
freq[ch] =[Link](ch, 0) +1
returnfreq
print(frequency("apple"))
character
string
cipher
palindrome
reverse
alphabet
➡️ Think:
STRING TRAVERSAL + ASCII
Odd/Even Check
Binary Conversion
Power of 2
Main Idea
Work directly on binary bits.
XOR Properties
a ⊕ a=0
a ⊕ 0=a
Python Code
PythonRundefunique_element(arr):
result=0
fornuminarr:
result^=num
returnresult
arr= [4, 1, 2, 1, 2]
print(unique_element(arr))
ifn&1:
return"Odd"
return"Even"
print(odd_even(7))
Why It Works
Binary:
Formula:
n ⊕ ( 1≪ k )
Python Code
PythonRundeftoggle_bit(n, k):
returnn^ (1<<k)
print(toggle_bit(5, 1))
returnbin(n)[2:]
print(decimal_to_binary(10))
Time Complexity
Usually:
O(1)
binary
bits
toggle
XOR
unique
parity
➡️ Think:
BIT MANIPULATION
Sort 0s/1s/2s
Rank Transformation
Sort by Frequency
Kth Largest/Smallest
n=len(arr)
foriinrange(n):
forjinrange(0, n-i-1):
ifarr[j] >arr[j+1]:
arr= [5, 1, 4, 2, 8]
print(bubble_sort(arr))
Python Code
PythonRundefsort_012(arr):
low=0
mid=0
high=len(arr) -1
whilemid<=high:
ifarr[mid] ==0:
low+=1
mid+=1
elifarr[mid] ==1:
mid+=1
else:
high-=1
returnarr
arr= [0, 2, 1, 2, 0, 1]
print(sort_012(arr))
[4, 5, 6, 5, 4, 3]
Output:
[4, 4, 5, 5, 6, 3]
Python Code
PythonRundefsort_by_frequency(arr):
freq= {}
fornuminarr:
freq[num] =[Link](num, 0) +1
returnarr
arr= [4, 5, 6, 5, 4, 3]
print(sort_by_frequency(arr))
returnarr[k-1]
print(kth_largest(arr, 2))
Time Complexities
Sorting Complexity
Bubble Sort O(n²)
order
arrange
rank
kth
sort colors
frequency sort
➡️ Think:
SORTING TECHNIQUES
Pattern 8 — Matrix Traversal
Used in:
Transpose Matrix
Spiral Traversal
Diagonal Sum
Main Idea
Traverse 2D arrays using:
rows
columns
foriinrange(len(matrix)):
forjinrange(len(matrix[0])):
i → row
j → column
Python Code
PythonRundeftranspose(matrix):
rows=len(matrix)
cols=len(matrix[0])
result= []
forjinrange(cols):
new_row= []
foriinrange(rows):
new_row.append(matrix[i][j])
[Link](new_row)
returnresult
matrix= [
[1, 2, 3],
[4, 5, 6]
]
print(transpose(matrix))
max_count=0
row_index=-1
foriinrange(len(matrix)):
count=matrix[i].count(1)
ifcount>max_count:
max_count=count
row_index=i
returnrow_index
matrix= [
[0, 1, 1],
[1, 1, 1],
[0, 0, 1]
]
print(row_max_ones(matrix))
foriinrange(len(matrix)):
total+=matrix[i][i]
returntotal
matrix= [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
print(diagonal_sum(matrix))
Time Complexity
Operation Complexity
Matrix Traversal O(rows × cols)
rows
columns
matrix
parking slots
transpose
diagonal
➡️ Think:
2D ARRAY TRAVERSAL
Prime Check
Leap Year
Armstrong Number
Fibonacci
Factorial
GCD/LCM
i ≤ √n
Python Code
PythonRundefis_prime(n):
ifn<2:
returnFalse
i=2
whilei*i<=n:
ifn%i==0:
returnFalse
i+=1
returnTrue
print(is_prime(17))
Python Code
PythonRundefleap_year(year):
if (year%400==0) or (year%4==0andyear%100!=0):
returnTrue
returnFalse
print(leap_year(2024))
153
Because:
original=n
power=len(str(n))
total=0
whilen>0:
digit=n%10
total+=digit**power
n//=10
returntotal==original
print(armstrong(153))
Example 4 — Fibonacci
Python Code
PythonRundeffibonacci(n):
a=0
b=1
foriinrange(n):
a, b=b, a+b
fibonacci(7)
Example 5 — GCD
Python Code
PythonRundefgcd(a, b):
whileb!=0:
a, b=b, a%b
returna
print(gcd(12, 18))
divisibility
prime
factorial
fibonacci
digits
number property
➡️ Think:
NUMBER THEORY
Pattern 10 — Input Handling (VERY IMPORTANT
FOR TCS)
TCS compiler is strict.
complete program
inputs
outputs
functions
imports
n=int(input())
arr=list(map(int, input().split()))
result=sum(arr)
print(result)
solve()
2. Multiple Integers
PythonRuna, b=map(int, input().split())
3. Array Input
PythonRunarr=list(map(int, input().split()))
4. Matrix Input
PythonRunrows=int(input())
cols=int(input())
matrix= []
foriinrange(rows):
row=list(map(int, input().split()))
[Link](row)
5. String Input
PythonRuns=input()
IMPORTANT TCS TIPS
Tip Why Important
Handle invalid input Frequently tested
Avoid extra spaces Strict checker
Print exact output Case-sensitive
Use iterative methods Faster
Avoid unnecessary imports Cleaner
Hashing
Two Pointer
Prefix Sum
Matrix
Bit Manipulation
Number Theory
minimum=arr[0]
fornuminarr:
ifnum<minimum:
minimum=num
returnminimum
arr= [4, 2, 7, 1, 9]
print(smallest(arr))
maximum=arr[0]
fornuminarr:
ifnum>maximum:
maximum=num
returnmaximum
arr= [4, 2, 7, 1, 9]
print(largest(arr))
3. Find Second Smallest and Second Largest
Python Code
PythonRundefsecond_smallest_largest(arr):
arr=list(set(arr))
[Link]()
second_smallest=arr[1]
second_largest=arr[-2]
returnsecond_smallest, second_largest
arr= [4, 2, 7, 1, 9]
print(second_smallest_largest(arr))
left=0
right=len(arr) -1
whileleft<right:
left+=1
right-=1
returnarr
arr= [1, 2, 3, 4, 5]
print(reverse_array(arr))
freq= {}
fornuminarr:
freq[num] =[Link](num, 0) +1
returnfreq
arr= [1, 2, 2, 3, 1, 4]
print(frequency(arr))
[1, 2, 3, 4, 5, 6]
↓
[1, 2, 3, 6, 5, 4]
Python Code
PythonRundefrearrange(arr):
[Link]()
mid=len(arr) //2
first=arr[:mid]
second=arr[mid:]
[Link]()
returnfirst+second
arr= [1, 2, 3, 4, 5, 6]
print(rearrange(arr))
total=0
fornuminarr:
total+=num
returntotal
arr= [1, 2, 3, 4]
print(array_sum(arr))
8. Rotate Array by K Elements
Python Code
PythonRundefrotate_array(arr, k):
n=len(arr)
k=k%n
returnarr[-k:] +arr[:-k]
arr= [1, 2, 3, 4, 5]
print(rotate_array(arr, 2))
Python Code
PythonRundefaverage(arr):
returnsum(arr) /len(arr)
arr= [1, 2, 3, 4, 5]
print(average(arr))
10. Find Median of Array
Python Code
PythonRundefmedian(arr):
[Link]()
n=len(arr)
mid=n//2
ifn%2==0:
return (arr[mid-1] +arr[mid]) /2
returnarr[mid]
arr= [7, 1, 3, 4, 5]
print(median(arr))
result= [arr[0]]
foriinrange(1, len(arr)):
ifarr[i] !=arr[i-1]:
[Link](arr[i])
returnresult
arr= [1, 1, 2, 2, 3, 4, 4]
print(remove_duplicates_sorted(arr))
returnlist(set(arr))
arr= [4, 2, 1, 2, 4, 5]
print(remove_duplicates_unsorted(arr))
[Link](element)
returnarr
arr= [1, 2, 3]
print(add_element(arr, 4))
14. Find All Repeating Elements
Python Code
PythonRundefrepeating_elements(arr):
freq= {}
result= []
fornuminarr:
freq[num] =[Link](num, 0) +1
forkey, [Link]():
ifvalue>1:
[Link](key)
returnresult
arr= [1, 2, 2, 3, 4, 4, 5]
print(repeating_elements(arr))
freq= {}
result= []
fornuminarr:
freq[num] =[Link](num, 0) +1
forkey, [Link]():
ifvalue==1:
[Link](key)
returnresult
arr= [1, 2, 2, 3, 4, 4, 5]
print(non_repeating(arr))
Traversal
Sorting
Hashing
Two Pointer
Prefix Sum
Example
Input:
Output:
(2, 1)
Python Code
PythonRundefsymmetric_pairs(pairs):
seen=set()
fora, binpairs:
if (b, a) inseen:
print((a, b))
[Link]((a, b))
symmetric_pairs(pairs)
2. Maximum Product Subarray
Find contiguous subarray with maximum product.
Example
Input:
[2, 3, -2, 4]
Output:
Python Code
PythonRundefmax_product(arr):
maximum=arr[0]
minimum=arr[0]
result=arr[0]
foriinrange(1, len(arr)):
ifarr[i] <0:
maximum, minimum=minimum, maximum
maximum=max(arr[i], maximum*arr[i])
minimum=min(arr[i], minimum*arr[i])
result=max(result, maximum)
returnresult
print(max_product(arr))
3. Replace Each Element by Rank
Smallest element gets rank 1.
Python Code
PythonRundefreplace_by_rank(arr):
sorted_unique=sorted(set(arr))
rank= {}
foriinrange(len(sorted_unique)):
rank[sorted_unique[i]] =i+1
result= []
fornuminarr:
[Link](rank[num])
returnresult
print(replace_by_rank(arr))
Python Code
PythonRundefsort_by_frequency(arr):
freq= {}
fornuminarr:
freq[num] =[Link](num, 0) +1
returnarr
arr= [4, 5, 6, 5, 4, 3]
print(sort_by_frequency(arr))
Right Rotation
Python Code
PythonRundefright_rotate(arr, k):
n=len(arr)
k=k%n
returnarr[-k:] +arr[:-k]
arr= [1, 2, 3, 4, 5]
print(right_rotate(arr, 2))
Left Rotation
Python Code
PythonRundefleft_rotate(arr, k):
n=len(arr)
k=k%n
returnarr[k:] +arr[:k]
arr= [1, 2, 3, 4, 5]
print(left_rotate(arr, 2))
6. Equilibrium Index
Left sum = Right sum
Python Code
PythonRundefequilibrium_index(arr):
total_sum=sum(arr)
left_sum=0
foriinrange(len(arr)):
total_sum-=arr[i]
ifleft_sum==total_sum:
returni
left_sum+=arr[i]
return-1
arr= [1, 3, 5, 2, 2]
print(equilibrium_index(arr))
Python Code
PythonRundefcircular_rotation(arr, k):
n=len(arr)
k=k%n
returnarr[-k:] +arr[:-k]
arr= [1, 2, 3, 4, 5]
print(circular_rotation(arr, 3))
Example
Input:
arr1 = [2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8]
arr2 = [2, 1, 8, 3]
Output:
[2, 2, 1, 1, 8, 8, 3, 5, 6, 7, 9]
Python Code
PythonRundefrelative_sort(arr1, arr2):
result= []
fornuminarr2:
whilenuminarr1:
[Link](num)
[Link](num)
[Link]()
returnresult+arr1
arr1= [2, 1, 2, 5, 7, 1, 9, 3, 6, 8, 8]
arr2= [2, 1, 8, 3]
print(relative_sort(arr1, arr2))
Linear Search
PythonRundeflinear_search(arr, target):
foriinrange(len(arr)):
ifarr[i] ==target:
returni
return-1
arr= [4, 2, 7, 1, 9]
print(linear_search(arr, 7))
left=0
right=len(arr) -1
whileleft<=right:
ifarr[mid] ==target:
returnmid
elifarr[mid] <target:
left=mid+1
else:
right=mid-1
return-1
arr= [1, 2, 4, 5, 7, 9]
print(binary_search(arr, 5))
Python Code
PythonRundefis_subset(arr1, arr2):
returnset(arr2).issubset(set(arr1))
arr1= [1, 2, 3, 4, 5]
arr2= [2, 4]
print(is_subset(arr1, arr2))
Infosys
Wipro
Cognizant
Example:
121 → Palindrome
Python Code
PythonRundefpalindrome(n):
original=n
reverse=0
whilen>0:
digit=n%10
reverse=reverse*10+digit
n//=10
returnoriginal==reverse
print(palindrome(121))
2. Print Palindrome Numbers in a Range
Python Code
PythonRundefis_palindrome(n):
returnstr(n) ==str(n)[::-1]
start=10
end=150
foriinrange(start, end+1):
ifis_palindrome(i):
print(i, end=" ")
i ≤ √n
Python Code
PythonRundefis_prime(n):
ifn<2:
returnFalse
i=2
whilei*i<=n:
ifn%i==0:
returnFalse
i+=1
returnTrue
print(is_prime(17))
ifn<2:
returnFalse
i=2
whilei*i<=n:
ifn%i==0:
returnFalse
i+=1
returnTrue
start=10
end=50
foriinrange(start, end+1):
ifis_prime(i):
print(i, end=" ")
5. Armstrong Number
Example:
153
Because:
Python Code
PythonRundefarmstrong(n):
original=n
power=len(str(n))
total=0
whilen>0:
digit=n%10
total+=digit**power
n//=10
returntotal==original
print(armstrong(153))
6. Perfect Number
Perfect number:
Sum of factors = number
Example:
1+2+3=6
Python Code
PythonRundefperfect_number(n):
total=0
foriinrange(1, n):
ifn%i==0:
total+=i
returntotal==n
print(perfect_number(6))
Python Code
PythonRundefeven_odd(n):
ifn%2==0:
return"Even"
return"Odd"
print(even_odd(7))
ifn>0:
return"Positive"
elifn<0:
return"Negative"
return"Zero"
print(positive_negative(-5))
n ( n+1 )
s u m=
2
Python Code
PythonRundefnatural_sum(n):
print(natural_sum(10))
print(ap_sum(2, 3, 5))
( r n −1 )
S n =a
r −1
Python Code
PythonRundefgp_sum(a, r, n):
print(gp_sum(2, 2, 5))
ifa>b:
returna
returnb
print(greatest_two(10, 20))
returnmax(a, b, c)
Python Code
PythonRundefleap_year(year):
if (year%400==0) or (year%4==0andyear%100!=0):
returnTrue
returnFalse
print(leap_year(2024))
15. Reverse Digits of a Number
Python Code
PythonRundefreverse_number(n):
reverse=0
whilen>0:
digit=n%10
reverse=reverse*10+digit
n//=10
returnreverse
print(reverse_number(1234))
digits=list(str(n))
maximum=max(digits)
minimum=min(digits)
returnmaximum, minimum
print(max_min_digit(583920))
17. Fibonacci Series
Python Code
PythonRundeffibonacci(n):
a=0
b=1
foriinrange(n):
a, b=b, a+b
fibonacci(10)
n !=n × ( n − 1 ) × ( n − 2 ) …1
Python Code
PythonRundeffactorial(n):
result=1
foriinrange(1, n+1):
result*=i
returnresult
print(factorial(5))
Important Number Patterns
Problem Pattern
Palindrome Reverse Number
Prime Divisibility
Armstrong Digit Power Sum
Perfect Number Factors
Fibonacci Iteration
Factorial Multiplication Loop
AP/GP Mathematical Formula
Even/Odd Modulo / Bit
loop-based
formula based
divisibility based
Problems on Numbers — TCS NQT Practice (Part
2)
p o w e r=ab
Python Code
PythonRundefpower(a, b):
returna**b
print(power(2, 5))
foriinrange(1, n+1):
ifn%i==0:
print(i, end=" ")
factors(12)
3. Print Prime Factors of a Number
Python Code
PythonRundefprime_factors(n):
i=2
whilei*i<=n:
whilen%i==0:
n//=i
i+=1
ifn>1:
print(n)
prime_factors(84)
4. Strong Number
A number whose sum of factorials of digits equals the number.
Example:
Python Code
PythonRundeffactorial(n):
result=1
foriinrange(1, n+1):
result*=i
returnresult
defstrong_number(n):
original=n
total=0
whilen>0:
digit=n%10
total+=factorial(digit)
n//=10
returntotal==original
print(strong_number(145))
5. Automorphic Number
Number whose square ends with the same digits.
Example:
252=625
Python Code
PythonRundefautomorphic(n):
square=n*n
returnstr(square).endswith(str(n))
print(automorphic(25))
Python Code
PythonRundefgcd(a, b):
whileb!=0:
a, b=b, a%b
returna
print(gcd(12, 18))
Python Code
PythonRundefgcd(a, b):
whileb!=0:
a, b=b, a%b
returna
deflcm(a, b):
print(lcm(12, 18))
8. Harshad Number
Number divisible by sum of digits.
Example:
18 ÷ ( 1+8 ) =2
Python Code
PythonRundefharshad(n):
digit_sum=sum(int(d) fordinstr(n))
returnn%digit_sum==0
print(harshad(18))
9. Abundant Number
Sum of proper divisors > number.
Example:
1+2+3+4+6>12
Python Code
PythonRundefabundant(n):
total=0
foriinrange(1, n):
ifn%i==0:
total+=i
returntotal>n
print(abundant(12))
total=0
whilen>0:
total+=n%10
n//=10
returntotal
print(sum_digits(1234))
11. Sum of Numbers in a Range
Python Code
PythonRundefrange_sum(start, end):
total=0
foriinrange(start, end+1):
total+=i
returntotal
print(range_sum(1, 10))
Python Code
PythonRunimportmath
defpermutation(n, r):
[Link](n) //[Link](n-r)
print(permutation(5, 2))
13. Add Two Fractions
Formula:
a c a d +b c
+ =
b d bd
Python Code
PythonRundefadd_fractions(a, b, c, d):
numerator=a*d+b*c
denominator=b*d
returnnumerator, denominator
print(add_fractions(1, 2, 3, 4))
returnint(str(n).replace('0', '1'))
print(replace_zero(1020))
ifn<2:
returnFalse
i=2
whilei*i<=n:
ifn%i==0:
returnFalse
i+=1
returnTrue
defsum_two_primes(n):
foriinrange(2, n):
ifis_prime(i) andis_prime(n-i):
returnTrue
returnFalse
print(sum_two_primes(34))
A r e a=π r 2
Python Code
PythonRunimportmath
defarea_circle(radius):
[Link] *radius*radius
print(area_circle(5))
− b ± √ b2 − 4 a c
x=
2a
Python Code
PythonRunimportmath
defquadratic_roots(a, b, c):
d=b*b-4*a*c
ifd<0:
return"Imaginary Roots"
returnroot1, root2
loops
divisibility
digit extraction
formulas
condition checking
Problems on Number System — TCS NQT
Practice
D e c i m a l=∑ ( b i t × 2 )
po sit ion
Python Code
PythonRundefbinary_to_decimal(binary):
returnint(binary, 2)
print(binary_to_decimal("1010"))
decimal=int(binary, 2)
returnoct(decimal)[2:]
print(binary_to_octal("101011"))
3. Convert Decimal to Binary
Python Code
PythonRundefdecimal_to_binary(n):
returnbin(n)[2:]
print(decimal_to_binary(10))
returnoct(n)[2:]
print(decimal_to_octal(25))
decimal=int(octal_num, 8)
returnbin(decimal)[2:]
print(octal_to_binary("25"))
6. Convert Octal to Decimal
Python Code
PythonRundefoctal_to_decimal(octal_num):
returnint(octal_num, 8)
print(octal_to_decimal("25"))
Example
Input:
123
Output:
Python Code
PythonRundefnumber_to_words(n):
words= {
'0': "Zero",
'1': "One",
'2': "Two",
'3': "Three",
'4': "Four",
'5': "Five",
'6': "Six",
'7': "Seven",
'8': "Eight",
'9': "Nine"
}
fordigitinstr(n):
number_to_words(1234)
binary
octal
conversion
bits
base system
➡️ Think:
NUMBER SYSTEM CONVERSION
Problems on Sorting
1. Bubble Sort
Repeatedly swap adjacent elements.
Python Code
PythonRundefbubble_sort(arr):
n=len(arr)
foriinrange(n):
forjinrange(0, n-i-1):
ifarr[j] >arr[j+1]:
returnarr
arr= [5, 1, 4, 2, 8]
print(bubble_sort(arr))
Time Complexity
O ( n2 )
2. Selection Sort
Select minimum element and place correctly.
Python Code
PythonRundefselection_sort(arr):
n=len(arr)
foriinrange(n):
minimum=i
forjinrange(i+1, n):
ifarr[j] <arr[minimum]:
minimum=j
returnarr
print(selection_sort(arr))
Time Complexity
O ( n2 )
3. Insertion Sort
Insert each element into correct position.
Python Code
PythonRundefinsertion_sort(arr):
foriinrange(1, len(arr)):
key=arr[i]
j=i-1
whilej>=0andarr[j] >key:
arr[j+1] =arr[j]
j-=1
arr[j+1] =key
returnarr
print(insertion_sort(arr))
Time Complexity
O ( n2 )
4. Quick Sort
Divide and conquer sorting.
Python Code
PythonRundefquick_sort(arr):
iflen(arr) <=1:
returnarr
pivot=arr[len(arr) //2]
left= [xforxinarrifx<pivot]
middle= [xforxinarrifx==pivot]
right= [xforxinarrifx>pivot]
returnquick_sort(left) +middle+quick_sort(right)
arr= [10, 7, 8, 9, 1, 5]
print(quick_sort(arr))
5. Merge Sort
Split array and merge sorted halves.
Python Code
PythonRundefmerge_sort(arr):
iflen(arr) >1:
mid=len(arr) //2
left=arr[:mid]
right=arr[mid:]
merge_sort(left)
merge_sort(right)
i=0
j=0
k=0
whilei<len(left) andj<len(right):
ifleft[i] <right[j]:
arr[k] =left[i]
i+=1
else:
arr[k] =right[j]
j+=1
k+=1
whilei<len(left):
arr[k] =left[i]
i+=1
k+=1
whilej<len(right):
arr[k] =right[j]
j+=1
k+=1
returnarr
print(merge_sort(arr))
Time Complexity
O ( n log n )
understanding logic
array manipulation
swapping
traversal
recursion basics
Example:
madam
Python Code
PythonRundefpalindrome(s):
returns==s[::-1]
print(palindrome("madam"))
2. Count Vowels, Consonants, and Spaces
Python Code
PythonRundefcount_characters(s):
vowels=0
consonants=0
spaces=0
[Link]():
ifchin"aeiou":
vowels+=1
[Link]():
consonants+=1
elifch==" ":
spaces+=1
print(count_characters("Hello World"))
returnord(ch)
print(ascii_value('A'))
ASCII Formula
A S C I I =o r d ( c h a r a c t e r )
result=""
forchins:
[Link]() notin"aeiou":
result+=ch
returnresult
print(remove_vowels("Programming"))
print(remove_spaces("Hello World"))
6. Remove Characters Except Alphabets
Python Code
PythonRundefalphabets_only(s):
result=""
forchins:
[Link]():
result+=ch
returnresult
print(alphabets_only("P@yth0n#123"))
7. Reverse a String
Python Code
PythonRundefreverse_string(s):
returns[::-1]
print(reverse_string("Python"))
(a+b)-c
↓
a+b-c
Python Code
PythonRundefremove_brackets(s):
brackets="(){}[]"
result=""
forchins:
ifchnotinbrackets:
result+=ch
returnresult
print(remove_brackets("(a+b)-{c}"))
ab12cd3
↓
15
Python Code
PythonRundefsum_numbers(s):
total=0
number=""
forchins:
[Link]():
number+=ch
else:
ifnumber!="":
total+=int(number)
number=""
ifnumber!="":
total+=int(number)
returntotal
print(sum_numbers("ab12cd3"))
hello world
↓
HellO WorlD
Python Code
PythonRundefcapitalize_words(s):
words=[Link]()
result= []
forwordinwords:
iflen(word) ==1:
[Link]([Link]())
else:
new_word= (
word[0].upper()
+word[1:-1]
+word[-1].upper()
)
[Link](new_word)
return" ".join(result)
print(capitalize_words("hello world"))
freq= {}
forchins:
freq[ch] =[Link](ch, 0) +1
returnfreq
print(character_frequency("apple"))
freq= {}
forchins:
freq[ch] =[Link](ch, 0) +1
result= []
forchins:
iffreq[ch] ==1:
[Link](ch)
returnresult
print(non_repeating("programming"))
listen
silent
Python Code
PythonRundefanagram(s1, s2):
returnsorted(s1) ==sorted(s2)
print(anagram("listen", "silent"))
count=0
forchinset(s1):
ifchins2:
count+=1
returncount
print(common_characters("apple", "plane"))
ASCII ord()
Reverse Slicing
Frequency Dictionary
Anagram sorted()
traversal
ASCII manipulation
hashing
slicing
condition checking
Example
a*b
axxxb
→ True
Python Code
PythonRundefwildcard_match(pattern, text):
p=0
t=0
star=-1
match=0
whilet<len(text):
p+=1
t+=1
star=p
match=t
p+=1
elifstar!=-1:
p=star+1
match+=1
t=match
else:
returnFalse
returnp==len(pattern)
print(wildcard_match("a*b", "axxxb"))
freq= {}
forchins:
freq[ch] =[Link](ch, 0) +1
maximum=max(freq, key=[Link])
returnmaximum
print(max_occurring("programming"))
3. Remove All Duplicates from a String
Python Code
PythonRundefremove_duplicates(s):
result=""
seen=set()
forchins:
ifchnotinseen:
result+=ch
[Link](ch)
returnresult
print(remove_duplicates("programming"))
freq= {}
forchins:
freq[ch] =[Link](ch, 0) +1
forkey, [Link]():
ifvalue>1:
print(key, end=" ")
duplicate_characters("programming")
Example
first = "computer"
second = "cat"
Output → "ompuer"
Python Code
PythonRundefremove_characters(s1, s2):
result=""
forchins1:
ifchnotins2:
result+=ch
returnresult
print(remove_characters("computer", "cat"))
Python Code
PythonRundefnext_alphabet(s):
result=""
forchins:
ifch=='z':
result+='a'
elifch=='Z':
result+='A'
else:
result+=chr(ord(ch) +1)
returnresult
print(next_alphabet("abc"))
words=[Link]()
largest=max(words, key=len)
returnlargest
return"".join(sorted(s))
print(sort_string("python"))
returnlen([Link]())
Python Code
PythonRundefrepeated_letters(word):
freq= {}
forchinword:
freq[ch] =[Link](ch, 0) +1
returnmax([Link]())
defhighest_repeated_word(s):
words=[Link]()
answer=""
maximum=0
forwordinwords:
current=repeated_letters(word)
ifcurrent>maximum:
maximum=current
answer=word
returnanswer
Python Code
PythonRundefchange_case(s):
result=""
forchins:
[Link]():
result+=[Link]()
else:
result+=[Link]()
returnresult
print(change_case("PyThOn"))
returns1+s2
[Link](sub)
print(substring_position("programming", "gram"))
Example
Hello World
↓
World Hello
Python Code
PythonRundefreverse_words(s):
words=[Link]()
[Link]()
return" ".join(words)
print(reverse_words("Hello World"))
Important String Patterns Used
Problem Pattern
Wildcard Matching Two Pointer
Frequency Count HashMap
Duplicate Removal Set
ASCII Shift ASCII Manipulation
Largest Word Traversal
Word Count Split
Reverse Words List Reversal
Frequency Dictionary
Sorting sorted()
hashing
ASCII manipulation
word operations
condition handling