0% found this document useful (0 votes)
5 views129 pages

Coding Problems - Python Array Problems

Uploaded by

SSPriya SSPriya
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)
5 views129 pages

Coding Problems - Python Array Problems

Uploaded by

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

1.

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

while mid <= high:

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

Python Code (Moore’s Voting Algorithm)


PythonRundef majority_element(arr):

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

for num in arr:


freq[num] = [Link](num, 0) + 1

result = []

for num in arr:


if freq[num] == 1:
[Link](num)

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

# Move non-zero elements forward


for i in range(len(arr)):

if arr[i] != 0:
arr[position], arr[i] = arr[i], arr[position]
position += 1

return arr

arr = [0, 1, 0, 3, 12]


print(move_zeros(arr))

Time Complexity
O(n)

TCS NQT Quick Revision Tips


Problem Main Concept
Equilibrium Index Prefix Sum
Sort 0s 1s 2s Three Pointer
Majority Element Moore Voting
Non-Repeating Elements HashMap / Dictionary
Problem Main Concept
Move Zeros to End Two Pointer

These are super common in TCS-style coding rounds because they test:

 Arrays

 Optimization

 Hashing

 Pointer logic

 Problem-solving speed

You're making the right kind of notes for NQT prep.

6. Replace Elements by Rank


Replace each element with its rank.
Smallest element → Rank 1

Equal elements get same rank.

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

arr= [40, 10, 20, 30, 20]


print(replace_by_rank(arr))

Time Complexity
O(n log n)

7. Prior Element Count


Count elements greater than all previous elements.

First element is always counted.

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)

8. Two Sum (Sorted Array)


Find two indices whose values add up to target.

Use Two Pointer Approach.

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

arr= [1, 2, 4, 6, 10]


target=8

print(two_sum_sorted(arr, target))

Time Complexity
O(n)

9. Count Unique / Distinct Elements


Find number of distinct elements.
Example
Input: [1, 2, 2, 3, 4, 4, 5]
Output: 5

Distinct elements → {1, 2, 3, 4, 5}

Python Code
PythonRundefcount_distinct(arr):

returnlen(set(arr))

arr= [1, 2, 2, 3, 4, 4, 5]
print(count_distinct(arr))

Time Complexity
O(n)

10. Kth Largest / Smallest Element


Return Kth largest or smallest element.

Duplicates are counted.

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]

arr= [7, 10, 4, 3, 20, 15]


k=3

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]

arr= [7, 10, 4, 3, 20, 15]


k=2

print(kth_largest(arr, k))
Time Complexity
O(n log n)

TCS NQT Quick Concepts Table


Problem Main Concept
Replace Elements by Rank Sorting + HashMap
Prior Element Count Running Maximum
Two Sum (Sorted) Two Pointers
Count Distinct Elements Set
Kth Largest/Smallest Sorting

These are frequently asked because they test:

 Array traversal

 Sorting

 Hashing

 Optimization

 Two-pointer logic

21. Transpose of a Matrix


Rows become columns.

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:

Because row index 2 has maximum 1s.

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)

23. Odd Occurring Element in Array


Every element appears twice except one.

Find unique element using XOR.

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

Duplicate elements cancel each other.

Time Complexity
O(n)

24. Sunday Counter


Given:

 Starting day

 Total days in month

Count number of Sundays.

Example
Input:

Starting Day = Monday


Total Days = 30

Output:

Logic
 Sunday occurs every 7 days.
 Find first Sunday position.

 Continue counting every 7th day.

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

If candies fall below K, refill to N.

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]

sold, remaining=candy_jar(capacity, threshold, orders)

print("Total Sold:", sold)


print("Remaining Candies:", remaining)

Time Complexity
O(n)

TCS NQT Quick Concepts Table


Problem Main Concept
Transpose Matrix Matrix Traversal
Row with Maximum 1s Counting
Odd Occurring Element XOR
Sunday Counter Modulo Arithmetic
Candy Jar Simulation Simulation Logic
These are very common in:

 TCS NQT

 Infosys

 Cognizant

 Wipro

 Capgemini

because they test:

 Logic building

 Array/Matrix handling

 Simulation thinking

 XOR tricks

 Traversal concepts

Pattern 1 — Hashing / Frequency Counting


Used in:

 First Non-Repeating Character

 Majority Element

 Count Distinct Elements

 Odd Occurring Element

 Character Frequency

 Balloon/Color Counting Problems

Main Idea
Store:
 element → count

using:

 Dictionary (dict)

 HashMap

 Set

Basic Template
PythonRunfreq= {}

foriteminarr:
freq[item] =[Link](item, 0) +1

print(freq)

Example 1 — Count Frequency


Input:

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

Example 2 — First Non-Repeating Element


Input:

[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 Count O(n)

TCS NQT Shortcut Thinking


Whenever question says:

 frequency

 repeating

 duplicate

 unique
 count occurrence

 majority

 non-repeating

➡️ Think:
HASHMAP / DICTIONARY

Pattern 2 — Two Pointer Technique


Used in:

 Two Sum

 Sort 0s 1s 2s

 Remove Duplicates

 Move Zeros

 Reverse Array

 Equilibrium Problems

Main Idea
Use:

 Left pointer

 Right pointer

Move pointers based on condition.


Basic Template
PythonRunleft=0
right=len(arr) -1

whileleft<right:

ifcondition:
left+=1
else:
right-=1

Example 1 — Two Sum (Sorted)


Input:

[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

arr= [1, 2, 4, 6, 10]

print(two_sum(arr, 8))

Example 2 — Move Zeros to End


PythonRundefmove_zeros(arr):

position=0

foriinrange(len(arr)):

ifarr[i] !=0:
arr[position], arr[i] =arr[i], arr[position]
position+=1

returnarr

arr= [0, 1, 0, 3, 12]

print(move_zeros(arr))

Example 3 — Reverse Array


PythonRundefreverse_array(arr):

left=0
right=len(arr) -1
whileleft<right:

arr[left], arr[right] =arr[right], arr[left]

left+=1
right-=1

returnarr

arr= [1, 2, 3, 4]

print(reverse_array(arr))

Pointer Movement Logic


Situation Action
Sum too small Move left
Sum too large Move right
Swap needed Move both
Reverse Move inward

Time Complexity
Usually:

O(n)

TCS NQT Shortcut Thinking


Whenever question says:

 sorted array

 pair sum
 reverse

 move elements

 partition

 swap

➡️ Think:
TWO POINTER

Pattern 3 — Prefix Sum / Running Sum


Used in:

 Equilibrium Index

 Range Sum Queries

 Maximum Guests

 Subarray Sum

 Running Total Problems

Main Idea
Store cumulative sums.

Instead of recalculating sum every time.

Prefix Sum Formula


p r e f i x [ i ] = p r e f i x [ i − 1 ] +a r r [ i ]
Example
Input:

[2, 4, 6, 8]

Prefix Sum:

[2, 6, 12, 20]

Python Code
PythonRundefprefix_sum(arr):

prefix= [0] *len(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))

Range Sum Query


Find sum from index L to R.

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]

Find sum from index 1 to 3

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

Equilibrium Index Logic


Left sum:

prefix[i - 1]

Right sum:

total_sum - prefix[i]

If equal:

equilibrium index found


Time Complexity
Method Complexity
Normal repeated sum O(n²)

Prefix Sum O(n)

TCS NQT Shortcut Thinking


Whenever question says:

 cumulative

 running total

 subarray sum

 equilibrium

 range sum

➡️ Think:
PREFIX SUM

Pattern 4 — Scenario-Based Mathematical Logic


Used in:

 Automobile Production

 Candy Jar

 Fare Calculation

 Triplets Equality

 Washing Machine Logic

 Ticket Billing
 Salary Calculation

 Water Tank Problems

Main Idea
Convert:

Story → Formula / Conditions

These problems mainly test:

 Logical thinking

 Condition handling

 Edge cases

 Simulation

MOST IMPORTANT RULE


Always check:

INVALID INPUT

TCS loves edge-case checking.

Common Invalid Cases


Situation Return
Negative number Invalid Input
Empty array/string Invalid Input
Impossible condition -1
Division by zero Handle safely
General Template
PythonRundefsolve_problem(data):

# Invalid input check


ifinvalid_condition:
return"Invalid Input"

# Main logic
result=formula_or_simulation

returnresult

Example 1 — Candy Jar Logic


Problem:

 Capacity = N

 Threshold = K

 Orders given

 Refill when candies become less than K

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

print(candy_jar(10, 5, [2, 3, 5, 4]))

Example 2 — Fare Calculation


Rules:

 First 5 km → ₹10/km

 After 5 km → ₹8/km

Python Code
PythonRundeffare(distance):

ifdistance<0:
return"Invalid Input"

ifdistance<=5:
returndistance*10

return (5*10) + ((distance-5) *8)

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

TCS NQT Shortcut Thinking


Whenever question gives:

 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

Important ASCII Functions


Function Meaning
ord(char) Character → ASCII
chr(number) ASCII → Character
lower() Lowercase
upper() Uppercase
Function Meaning
isalpha() Check alphabet
isdigit() Check digit

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

Example 3 — Caesar Cipher


Shift each character by K positions.

Python Code
PythonRundefcaesar_cipher(text, shift):

result=""

forchintext:

[Link]():

start=ord('A') [Link]() elseord('a')

new_char=chr((ord(ch) -start+shift) %26+start)

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

TCS NQT Shortcut Thinking


Whenever question says:

 character

 string

 cipher

 palindrome

 reverse

 alphabet

➡️ Think:
STRING TRAVERSAL + ASCII

Pattern 6 — Bit Manipulation


Used in:

 XOR Unique Element


 Toggle Bits

 Odd/Even Check

 Binary Conversion

 Swap Without Temp

 Power of 2

Main Idea
Work directly on binary bits.

Most Important Operators


Operator Meaning
& AND
` `
^ XOR
~ NOT
<< Left Shift
>> Right Shift

XOR Properties
a ⊕ a=0

a ⊕ 0=a

These are SUPER IMPORTANT for TCS.


Example 1 — Unique Element
Every element appears twice except one.

Python Code
PythonRundefunique_element(arr):

result=0

fornuminarr:
result^=num

returnresult

arr= [4, 1, 2, 1, 2]

print(unique_element(arr))

Example 2 — Odd or Even


Python Code
PythonRundefodd_even(n):

ifn&1:
return"Odd"

return"Even"

print(odd_even(7))
Why It Works
Binary:

Even → last bit = 0


Odd → last bit = 1

Example 3 — Toggle Bit


Toggle kth bit.

Formula:

n ⊕ ( 1≪ k )

Python Code
PythonRundeftoggle_bit(n, k):

returnn^ (1<<k)

print(toggle_bit(5, 1))

Example 4 — Decimal to Binary


PythonRundefdecimal_to_binary(n):

returnbin(n)[2:]

print(decimal_to_binary(10))
Time Complexity
Usually:

O(1)

TCS NQT Shortcut Thinking


Whenever question says:

 binary

 bits

 toggle

 XOR

 unique

 parity

➡️ Think:
BIT MANIPULATION

Pattern 7 — Sorting Variants


Used in:

 Sort 0s/1s/2s

 Rank Transformation

 Sort by Frequency

 Kth Largest/Smallest

 Bubble/Selection/Insertion Sort Questions


Main Idea
Know:

 when to use built-in sorting

 when NOT to use it

 in-place sorting techniques

Important Sorting Types


Sorting Best Use
Bubble Sort Small/basic problems
Selection Sort Minimum swaps
Insertion Sort Nearly sorted arrays
Built-in sort() Fast general sorting
Dutch National Flag 0s 1s 2s
Custom Sort Frequency/rank problems

Example 1 — Bubble Sort


Python Code
PythonRundefbubble_sort(arr):

n=len(arr)

foriinrange(n):

forjinrange(0, n-i-1):

ifarr[j] >arr[j+1]:

arr[j], arr[j+1] =arr[j+1], arr[j]


returnarr

arr= [5, 1, 4, 2, 8]

print(bubble_sort(arr))

Example 2 — Sort 0s, 1s, 2s


(Dutch National Flag)

Python Code
PythonRundefsort_012(arr):

low=0
mid=0
high=len(arr) -1

whilemid<=high:

ifarr[mid] ==0:

arr[low], arr[mid] =arr[mid], arr[low]

low+=1
mid+=1

elifarr[mid] ==1:

mid+=1

else:

arr[mid], arr[high] =arr[high], arr[mid]

high-=1

returnarr
arr= [0, 2, 1, 2, 0, 1]

print(sort_012(arr))

Example 3 — Sort by Frequency


Input:

[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

[Link](key=lambdax: (-freq[x], x))

returnarr

arr= [4, 5, 6, 5, 4, 3]

print(sort_by_frequency(arr))

Example 4 — Kth Largest


PythonRundefkth_largest(arr, k):
[Link](reverse=True)

returnarr[k-1]

arr= [7, 10, 4, 3, 20, 15]

print(kth_largest(arr, 2))

Time Complexities
Sorting Complexity
Bubble Sort O(n²)

Selection Sort O(n²)

Insertion Sort O(n²)

Built-in Sort O(n log n)

TCS NQT Shortcut Thinking


Whenever question says:

 order

 arrange

 rank

 kth

 sort colors

 frequency sort

➡️ Think:
SORTING TECHNIQUES
Pattern 8 — Matrix Traversal
Used in:

 Transpose Matrix

 Row with Maximum 1s

 Parking Lot Problems

 Spiral Traversal

 Diagonal Sum

Main Idea
Traverse 2D arrays using:

 rows

 columns

Basic Matrix Traversal


Python Code
PythonRunmatrix= [
[1, 2, 3],
[4, 5, 6]
]

foriinrange(len(matrix)):

forjinrange(len(matrix[0])):

print(matrix[i][j], end=" ")


Matrix Index Formula
m a t r i x [i] [ j]

 i → row

 j → column

Example 1 — Transpose Matrix


Rows become columns.

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

Example 2 — Row with Maximum 1s


Python Code
PythonRundefrow_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, 1, 1],
[0, 0, 1]
]

print(row_max_ones(matrix))

Example 3 — Diagonal Sum


Python Code
PythonRundefdiagonal_sum(matrix):
total=0

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)

TCS NQT Shortcut Thinking


Whenever question says:

 rows

 columns

 matrix

 parking slots

 transpose

 diagonal

➡️ Think:
2D ARRAY TRAVERSAL

Pattern 9 — Number Theory Basics


Used in:

 Prime Check

 Leap Year

 Armstrong Number

 Fibonacci

 Factorial

 GCD/LCM

Example 1 — Prime Number


Main optimization:

i ≤ √n

Only check till √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))

Example 2 — Leap Year


Formula:

( y e a r mod 400=0 ) ∨ ( y e a r mod 4=0 ∧ y e a r mod 100 ≠ 0 )

Python Code
PythonRundefleap_year(year):

if (year%400==0) or (year%4==0andyear%100!=0):
returnTrue

returnFalse

print(leap_year(2024))

Example 3 — Armstrong Number


Example:

153

Because:

13 +53 +33 =153


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

Example 4 — Fibonacci
Python Code
PythonRundeffibonacci(n):

a=0
b=1

foriinrange(n):

print(a, end=" ")

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

TCS NQT Shortcut Thinking


Whenever question says:

 divisibility

 prime

 factorial

 fibonacci

 digits

 number property

➡️ Think:
NUMBER THEORY
Pattern 10 — Input Handling (VERY IMPORTANT
FOR TCS)
TCS compiler is strict.

You must write:

 complete program

 inputs

 outputs

 functions

 imports

Basic TCS Program Structure


Python Template
PythonRundefsolve():

n=int(input())

arr=list(map(int, input().split()))

result=sum(arr)

print(result)

solve()

Common Input Patterns


1. Single Integer
PythonRunn=int(input())

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

Golden Rule for TCS NQT


Understand Pattern > Memorize Code

Once you identify the pattern:

 Hashing

 Two Pointer

 Prefix Sum

 Matrix

 Bit Manipulation

 Number Theory

most TCS problems become much easier.

Problems on Arrays — TCS NQT Practice

1. Find the Smallest Number in an Array


Python Code
PythonRundefsmallest(arr):

minimum=arr[0]
fornuminarr:

ifnum<minimum:
minimum=num

returnminimum

arr= [4, 2, 7, 1, 9]

print(smallest(arr))

2. Find the Largest Number in an Array


Python Code
PythonRundeflargest(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))

4. Reverse a Given Array


Python Code
PythonRundefreverse_array(arr):

left=0
right=len(arr) -1

whileleft<right:

arr[left], arr[right] =arr[right], arr[left]

left+=1
right-=1

returnarr
arr= [1, 2, 3, 4, 5]

print(reverse_array(arr))

5. Count Frequency of Each Element


Python Code
PythonRundeffrequency(arr):

freq= {}

fornuminarr:
freq[num] =[Link](num, 0) +1

returnfreq

arr= [1, 2, 2, 3, 1, 4]

print(frequency(arr))

6. Rearrange Array in Increasing-Decreasing


Order
Example:

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

7. Calculate Sum of Elements


Python Code
PythonRundefarray_sum(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))

9. Find Average of Elements


Formula:
sumo f element s
a v e r a g e=
number o f element s

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

11. Remove Duplicates from Sorted Array


Python Code
PythonRundefremove_duplicates_sorted(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))

12. Remove Duplicates from Unsorted Array


Python Code
PythonRundefremove_duplicates_unsorted(arr):

returnlist(set(arr))

arr= [4, 2, 1, 2, 4, 5]

print(remove_duplicates_unsorted(arr))

13. Add an Element to an Array


Python Code
PythonRundefadd_element(arr, element):

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

15. Find All Non-Repeating Elements


Python Code
PythonRundefnon_repeating(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))

Important Array Patterns Used


Problem Pattern
Smallest/Largest Traversal
Frequency Count Hashing
Reverse Array Two Pointer
Rearrangement Sorting
Rotate Array Array Manipulation
Median Sorting
Remove Duplicates Set / Two Pointer
Repeating Elements HashMap

TCS NQT Last-Minute Tip


For arrays, MOST problems fall into:

 Traversal

 Sorting

 Hashing

 Two Pointer

 Prefix Sum

If you identify the pattern quickly, coding becomes much easier.


Problems on Arrays — TCS NQT Practice (Part 2)

1. Find All Symmetric Pairs in an Array


Symmetric pair:

(a, b) and (b, a)

Example
Input:

[(1, 2), (3, 4), (2, 1), (5, 6)]

Output:

(2, 1)

Python Code
PythonRundefsymmetric_pairs(pairs):

seen=set()

fora, binpairs:

if (b, a) inseen:
print((a, b))

[Link]((a, b))

pairs= [(1, 2), (3, 4), (2, 1), (5, 6)]

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

arr= [2, 3, -2, 4]

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

arr= [40, 10, 20, 30]

print(replace_by_rank(arr))

4. Sort Elements by Frequency


Higher frequency comes first.

Python Code
PythonRundefsort_by_frequency(arr):

freq= {}
fornuminarr:
freq[num] =[Link](num, 0) +1

[Link](key=lambdax: (-freq[x], x))

returnarr

arr= [4, 5, 6, 5, 4, 3]

print(sort_by_frequency(arr))

5. Rotate Array Left and Right

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

7. Circular Rotation by K Positions

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

8. Sort According to Another Array

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

9. Search an Element in an Array

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

Binary Search (Sorted Array)


PythonRundefbinary_search(arr, target):

left=0
right=len(arr) -1

whileleft<=right:

mid= (left+right) //2

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

10. Check if Array is Subset of Another Array

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

Important Patterns Used


Problem Pattern
Symmetric Pair HashSet
Max Product Subarray Kadane Variant
Rank Replacement Sorting + HashMap
Frequency Sort Hashing
Rotations Array Manipulation
Equilibrium Index Prefix Sum
Relative Sorting Custom Sorting
Searching Linear/Binary Search
Subset Check Set

TCS NQT Quick Revision


Topic Must Know
Arrays Traversal
Sorting Built-in + Logic
Searching Linear/Binary
Hashing Frequency Problems
Rotations Slicing Logic
Prefix Sum Equilibrium

These patterns repeat A LOT in:


 TCS NQT

 Infosys

 Wipro

 Cognizant

 Accenture coding rounds

Problems on Numbers — TCS NQT Practice

1. Check if a Number is Palindrome


A palindrome remains same after reversing.

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

3. Check if Number is Prime


Optimization:

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

4. Print Prime Numbers in a Range


Python Code
PythonRundefis_prime(n):

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:

13 +53 +33 =153

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

7. Check Even or Odd

Python Code
PythonRundefeven_odd(n):

ifn%2==0:
return"Even"

return"Odd"

print(even_odd(7))

8. Positive or Negative Number


Python Code
PythonRundefpositive_negative(n):

ifn>0:
return"Positive"

elifn<0:
return"Negative"

return"Zero"

print(positive_negative(-5))

9. Sum of First N Natural Numbers


Formula:

n ( n+1 )
s u m=
2

Python Code
PythonRundefnatural_sum(n):

returnn* (n+1) //2

print(natural_sum(10))

10. Sum of AP Series


Formula:
n
S n= [ 2 a+ ( n −1 ) d ]
2
Python Code
PythonRundefap_sum(a, d, n):

return (n* (2*a+ (n-1) *d)) //2

print(ap_sum(2, 3, 5))

11. Sum of GP Series


Formula:

( r n −1 )
S n =a
r −1

Python Code
PythonRundefgp_sum(a, r, n):

returna* ((r**n) -1) // (r-1)

print(gp_sum(2, 2, 5))

12. Greatest of Two Numbers


Python Code
PythonRundefgreatest_two(a, b):

ifa>b:
returna

returnb
print(greatest_two(10, 20))

13. Greatest of Three Numbers


Python Code
PythonRundefgreatest_three(a, b, c):

returnmax(a, b, c)

print(greatest_three(10, 25, 15))

14. Leap Year Check


Formula:

( y e a r mod 400=0 ) ∨ ( y e a r mod 4=0 ∧ y e a r mod 100 ≠ 0 )

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

16. Maximum and Minimum Digit


Python Code
PythonRundefmax_min_digit(n):

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

print(a, end=" ")

a, b=b, a+b

fibonacci(10)

18. Factorial of a Number


Formula:

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

TCS NQT Quick Revision


Topic Must Know
Prime √N optimization
Fibonacci Iterative approach
Factorial Loop multiplication
Armstrong Digit powers
Palindrome Reverse logic
AP/GP Direct formulas

Most number problems in TCS are:

 loop-based

 digit extraction based

 formula based

 divisibility based
Problems on Numbers — TCS NQT Practice (Part
2)

1. Find Power of a Number


Formula:

p o w e r=ab

Python Code
PythonRundefpower(a, b):

returna**b

print(power(2, 5))

2. Find Factors of a Number


Python Code
PythonRundeffactors(n):

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:

print(i, end=" ")

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:

1 !+4 !+5 !=145

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

6. GCD of Two Numbers


(Euclidean Algorithm)

Python Code
PythonRundefgcd(a, b):

whileb!=0:

a, b=b, a%b

returna

print(gcd(12, 18))

7. LCM of Two Numbers


Formula:
a×b
LC M=
G C D (a ,b)

Python Code
PythonRundefgcd(a, b):

whileb!=0:
a, b=b, a%b

returna
deflcm(a, b):

return (a*b) //gcd(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))

10. Sum of Digits


Python Code
PythonRundefsum_digits(n):

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

12. Permutations (N People Occupying R Seats)


Formula:
n!
P ( n , r )=
(n−r )!

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

14. Replace All 0s with 1s


Python Code
PythonRundefreplace_zero(n):

returnint(str(n).replace('0', '1'))

print(replace_zero(1020))

15. Sum of Two Prime Numbers


(Goldbach-like check)
Python Code
PythonRundefis_prime(n):

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

16. Area of a Circle


Formula:

A r e a=π r 2
Python Code
PythonRunimportmath

defarea_circle(radius):

[Link] *radius*radius

print(area_circle(5))

17. Roots of Quadratic Equation


Formula:

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

root1= (-b+[Link](d)) / (2*a)


root2= (-[Link](d)) / (2*a)

returnroot1, root2

print(quadratic_roots(1, -3, 2))


Important Number Patterns Used
Problem Pattern
Strong Number Factorial + Digits
Automorphic Square Check
GCD/LCM Euclidean Algorithm
Harshad Digit Sum
Abundant Factors
Prime Factors Divisibility
Fractions Formula
Quadratic Roots Mathematics

TCS NQT Quick Revision


Topic Key Trick
GCD Euclidean Algorithm
LCM (a*b)//gcd

Prime Factors Divide repeatedly


Strong Number Factorial of digits
Harshad Number % digit sum
Quadratic Discriminant

Most TCS number problems are combinations of:

 loops

 divisibility

 digit extraction

 formulas

 condition checking
Problems on Number System — TCS NQT
Practice

1. Convert Binary to Decimal


Formula:

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

2. Convert Binary to Octal


Python Code
PythonRundefbinary_to_octal(binary):

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

4. Convert Decimal to Octal


Python Code
PythonRundefdecimal_to_octal(n):

returnoct(n)[2:]

print(decimal_to_octal(25))

5. Convert Octal to Binary


Python Code
PythonRundefoctal_to_binary(octal_num):

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

7. Convert Digits/Numbers to Words

Example
Input:

123

Output:

One Two Three

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

print(words[digit], end=" ")

number_to_words(1234)

Important Number System Functions


Function Meaning
bin(n) Decimal → Binary
oct(n) Decimal → Octal
hex(n) Decimal → Hexadecimal
int(value, base) Convert to Decimal

TCS NQT Shortcut Thinking


Whenever question says:

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

arr[j], arr[j+1] =arr[j+1], arr[j]

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

arr[i], arr[minimum] =arr[minimum], arr[i]

returnarr

arr= [64, 25, 12, 22, 11]

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

arr= [12, 11, 13, 5, 6]

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

Average Time Complexity


O ( n log n )

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

arr= [12, 11, 13, 5, 6, 7]

print(merge_sort(arr))

Time Complexity
O ( n log n )

Sorting Algorithms Comparison


Best Worst
Algorithm Stable
Complexity Complexity
Bubble Sort O(n) O(n²) Yes
Selection Sort O(n²) O(n²) No
Insertion Sort O(n) O(n²) Yes
Quick Sort O(n log n) O(n²) No
Merge Sort O(n log n) O(n log n) Yes

TCS NQT Quick Revision


Topic Key Idea
Binary Conversion Base 2
Octal Conversion Base 8
Bubble Sort Adjacent Swap
Selection Sort Select Minimum
Insertion Sort Insert Correctly
Topic Key Idea
Quick Sort Pivot Partition
Merge Sort Divide & Merge

Most sorting questions in TCS focus on:

 understanding logic

 array manipulation

 swapping

 traversal

 recursion basics

Problems on Strings — TCS NQT Practice

1. Check if a String is Palindrome


A palindrome reads same forward and backward.

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

returnvowels, consonants, spaces

print(count_characters("Hello World"))

3. Find ASCII Value of a Character


Python Code
PythonRundefascii_value(ch):

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 )

4. Remove All Vowels from a String


Python Code
PythonRundefremove_vowels(s):

result=""

forchins:

[Link]() notin"aeiou":
result+=ch

returnresult

print(remove_vowels("Programming"))

5. Remove Spaces from a String


Python Code
PythonRundefremove_spaces(s):

[Link](" ", "")

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

8. Remove Brackets from Algebraic Expression


Example:

(a+b)-c

a+b-c
Python Code
PythonRundefremove_brackets(s):

brackets="(){}[]"

result=""

forchins:

ifchnotinbrackets:
result+=ch

returnresult

print(remove_brackets("(a+b)-{c}"))

9. Find Sum of Numbers in a String


Example:

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

10. Capitalize First and Last Character of Each


Word
Example:

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

11. Frequency of Characters


Python Code
PythonRundefcharacter_frequency(s):

freq= {}

forchins:

freq[ch] =[Link](ch, 0) +1

returnfreq

print(character_frequency("apple"))

12. Non-Repeating Characters


Python Code
PythonRundefnon_repeating(s):

freq= {}
forchins:

freq[ch] =[Link](ch, 0) +1

result= []

forchins:

iffreq[ch] ==1:
[Link](ch)

returnresult

print(non_repeating("programming"))

13. Check if Two Strings are Anagrams


Example:

listen
silent

Python Code
PythonRundefanagram(s1, s2):

returnsorted(s1) ==sorted(s2)

print(anagram("listen", "silent"))

14. Count Common Subsequences in Two Strings


Simple common character counting.
Python Code
PythonRundefcommon_characters(s1, s2):

count=0

forchinset(s1):

ifchins2:
count+=1

returncount

print(common_characters("apple", "plane"))

Important String Functions


Function Meaning
lower() Lowercase
upper() Uppercase
isalpha() Alphabet check
isdigit() Digit check
replace() Replace text
split() Split words
"".join() Join strings
ord() ASCII value

Important String Patterns


Problem Pattern
Palindrome Reverse
Problem Pattern
Frequency HashMap
Remove Characters Traversal
Sum in String Digit Extraction
Anagram Sorting
Reverse String Slicing
Character Count Traversal

TCS NQT Quick Revision


Topic Key Trick
Palindrome s[::-1]

ASCII ord()

Reverse Slicing
Frequency Dictionary
Anagram sorted()

Remove Spaces replace()

Most TCS string problems are based on:

 traversal

 ASCII manipulation

 hashing

 slicing

 condition checking

Problems on Strings — TCS NQT Practice (Part 2)


1. Check if Two Strings Match (Wildcard
Characters)
Wildcard:

 ? → matches single character

 * → matches multiple characters

Example
a*b
axxxb
→ True

Python Code
PythonRundefwildcard_match(pattern, text):

p=0
t=0
star=-1
match=0

whilet<len(text):

ifp<len(pattern) and (pattern[p] ==text[t] orpattern[p] =='?'):

p+=1
t+=1

elifp<len(pattern) andpattern[p] =='*':

star=p
match=t
p+=1

elifstar!=-1:
p=star+1
match+=1
t=match

else:
returnFalse

whilep<len(pattern) andpattern[p] =='*':


p+=1

returnp==len(pattern)

print(wildcard_match("a*b", "axxxb"))

2. Maximum Occurring Character


Python Code
PythonRundefmax_occurring(s):

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

4. Print Duplicate Characters


Python Code
PythonRundefduplicate_characters(s):

freq= {}

forchins:
freq[ch] =[Link](ch, 0) +1

forkey, [Link]():

ifvalue>1:
print(key, end=" ")
duplicate_characters("programming")

5. Remove Characters from First String Present


in Second String

Example
first = "computer"
second = "cat"

Output → "ompuer"

Python Code
PythonRundefremove_characters(s1, s2):

result=""

forchins1:

ifchnotins2:
result+=ch

returnresult

print(remove_characters("computer", "cat"))

6. Replace Each Letter with Next Lexicographic


Alphabet
Example:
abc → bcd

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

ASCII Shift Formula


n e x t =c h r ( o r d ( c h ) +1 )

7. Find Largest Word in a String


Python Code
PythonRundeflargest_word(s):

words=[Link]()
largest=max(words, key=len)

returnlargest

print(largest_word("I love programming very much"))

8. Sort Characters in a String


Python Code
PythonRundefsort_string(s):

return"".join(sorted(s))

print(sort_string("python"))

9. Count Number of Words


Python Code
PythonRundefword_count(s):

returnlen([Link]())

print(word_count("Welcome to Python Programming"))

10. Word with Highest Repeated Letters


Example
"apple banana success"

success

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

print(highest_repeated_word("apple banana success"))


11. Change Case of Each Character
Upper → Lower
Lower → Upper

Python Code
PythonRundefchange_case(s):

result=""

forchins:

[Link]():
result+=[Link]()

else:
result+=[Link]()

returnresult

print(change_case("PyThOn"))

12. Concatenate Strings


Python Code
PythonRundefconcatenate(s1, s2):

returns1+s2

print(concatenate("Hello ", "World"))


13. Find Substring Starting Position
Python Code
PythonRundefsubstring_position(s, sub):

[Link](sub)

print(substring_position("programming", "gram"))

14. Reverse Words in a String

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

Important ASCII Functions


Function Meaning
ord() Character → ASCII
chr() ASCII → Character
upper() Uppercase
lower() Lowercase
swapcase() Change Case

TCS NQT Quick Revision


Topic Key Trick
Reverse String [::-1]

Word Count split()

Frequency Dictionary
Sorting sorted()

Remove Duplicates Set


ASCII Conversion ord() + chr()

Most TCS string questions focus on:


 traversal

 hashing

 ASCII manipulation

 word operations

 condition handling

You might also like