0% found this document useful (0 votes)
77 views8 pages

Python Coding Interview Guide

The document provides a comprehensive reference for common coding problems and their Python solutions, covering topics such as prime checking, palindrome verification, string manipulation, and more. Each problem includes a description, a Python function, and example outputs. It also offers tips for coding interviews, emphasizing clarity of thought and edge case testing.

Uploaded by

Harshi99 1204
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)
77 views8 pages

Python Coding Interview Guide

The document provides a comprehensive reference for common coding problems and their Python solutions, covering topics such as prime checking, palindrome verification, string manipulation, and more. Each problem includes a description, a Python function, and example outputs. It also offers tips for coding interviews, emphasizing clarity of thought and edge case testing.

Uploaded by

Harshi99 1204
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

TCS: Common Coding Topics + Python Solutions

(Ready reference for interviews)


Generated on: 2025-12-24 12:06:46 Includes: Basic logic, Arrays, Strings, Patterns, Math problems,
Scenario-based problems, and more. All solutions in Python.

1. Check Prime Number

Problem: Given an integer n, check whether it is a prime number.

Python Solution:
def is_prime(n):
if n <= 1:
return False
if n <= 3:
return True
if n % 2 == 0:
return False
i = 3
while i * i <= n:
if n % i == 0:
return False
i += 2
return True

# Example
print(is_prime(17)) # True

2. Palindrome Number / String

Problem: Check whether a given number or string is a palindrome.

Python Solution:
def is_palindrome_str(s):
return s == s[::-1]

def is_palindrome_num(n):
s = str(n)
return is_palindrome_str(s)

# Examples
print(is_palindrome_str('radar')) # True
print(is_palindrome_num(121)) # True

3. Reverse a String

Problem: Reverse a given string without using reversed() (show slicing and manual).

Python Solution:
def reverse_string(s):
# using slicing
return s[::-1]

def reverse_string_manual(s):
res = []
for ch in s:
[Link](0, ch)
return ''.join(res)
# Example
print(reverse_string('hello')) # 'olleh'
print(reverse_string_manual('world')) # 'dlrow'

4. Fibonacci Series (nth term and list)

Problem: Print first n Fibonacci numbers and also find nth Fibonacci number.

Python Solution:
def fib_list(n):
res = []
a, b = 0, 1
for _ in range(n):
[Link](a)
a, b = b, a + b
return res

def fib_n(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a

# Example
print(fib_list(7)) # [0,1,1,2,3,5,8]
print(fib_n(6)) # 8 (0-indexed)

5. Factorial

Problem: Compute factorial of n (iterative and recursive).

Python Solution:
def factorial_iter(n):
res = 1
for i in range(2, n+1):
res *= i
return res

def factorial_rec(n):
return 1 if n <= 1 else n * factorial_rec(n-1)

# Example
print(factorial_iter(5)) # 120
print(factorial_rec(5)) # 120

6. Armstrong Number (n-digit Armstrong)

Problem: Check if a number is an Armstrong number (sum of nth powers of digits equals number).

Python Solution:
def is_armstrong(n):
s = str(n)
k = len(s)
return n == sum(int(ch)**k for ch in s)

# Example
print(is_armstrong(153)) # True (1^3 + 5^3 + 3^3)

7. Leap Year

Problem: Check if a year is a leap year.


Python Solution:
def is_leap(year):
return (year % 4 == 0 and year % 100 != 0) or (year % 400 == 0)

# Example
print(is_leap(2000)) # True
print(is_leap(1900)) # False

8. Count Vowels and Consonants

Problem: Given a string, count vowels and consonants (letters only).

Python Solution:
def count_vowels_consonants(s):
vowels = set('aeiouAEIOU')
v = c = 0
for ch in s:
if [Link]():
if ch in vowels:
v += 1
else:
c += 1
return v, c

# Example
print(count_vowels_consonants('Hello, World!')) # (3,7)

9. Sum of Digits

Problem: Return sum of digits of an integer (handle negative).

Python Solution:
def sum_of_digits(n):
n = abs(n)
s = 0
while n:
s += n % 10
n //= 10
return s

# Example
print(sum_of_digits(-1234)) # 10

10. Largest and Smallest in an Array

Problem: Find largest and smallest element in a list without built-ins.

Python Solution:
def min_max(arr):
if not arr:
return None, None
mn = mx = arr[0]
for x in arr[1:]:
if x < mn: mn = x
if x > mx: mx = x
return mn, mx

# Example
print(min_max([3,1,7,4,9])) # (1,9)

11. Second Largest Element


Problem: Find the second largest element in an array (handle duplicates).

Python Solution:
def second_largest(arr):
first = second = float('-inf')
for x in arr:
if x > first:
second = first
first = x
elif first > x > second:
second = x
return None if second == float('-inf') else second

# Example
print(second_largest([5,1,5,3,2])) # 3

12. Reverse an Array

Problem: Reverse elements of an array in-place and return new reversed copy.

Python Solution:
def reverse_array_inplace(arr):
i, j = 0, len(arr)-1
while i < j:
arr[i], arr[j] = arr[j], arr[i]
i += 1; j -= 1
return arr

def reverse_array_copy(arr):
return arr[::-1]

# Example
print(reverse_array_inplace([1,2,3,4])) # [4,3,2,1]
print(reverse_array_copy([1,2,3])) # [3,2,1]

13. Remove Duplicates (preserve order)

Problem: Remove duplicates from list while preserving original order.

Python Solution:
def remove_duplicates(arr):
seen = set()
res = []
for x in arr:
if x not in seen:
[Link](x)
[Link](x)
return res

# Example
print(remove_duplicates([1,2,3,2,1,4])) # [1,2,3,4]

14. Count Even and Odd Numbers

Problem: Given a list of integers, count how many are even and odd.

Python Solution:
def count_even_odd(arr):
ev = od = 0
for x in arr:
if x % 2 == 0:
ev += 1
else:
od += 1
return ev, od

# Example
print(count_even_odd([1,2,3,4,5])) # (2,3)

15. Anagram Check

Problem: Check whether two strings are anagrams of each other.

Python Solution:
def are_anagrams(a, b):
# quick normalize: remove spaces and lowercase
a = ''.join([Link]()).lower()
b = ''.join([Link]()).lower()
return sorted(a) == sorted(b)

# Example
print(are_anagrams('listen','silent')) # True

16. Character Frequency in String

Problem: Return frequency (count) of each character in a string.

Python Solution:
from collections import Counter
def char_freq(s):
return dict(Counter(s))

# Example
print(char_freq('abbccc')) # {'a':1,'b':2,'c':3}

17. Remove Spaces and Special Characters (keep alphanumeric)

Problem: Return a cleaned string with only alphanumeric characters (and optionally spaces).

Python Solution:
import re
def clean_alpha_num(s):
return [Link](r'[^A-Za-z0-9 ]+', '', s)

# Example
print(clean_alpha_num('Hello, World! 123')) # 'Hello World 123'

18. Pattern Printing (numeric & star)

Problem: Simple triangle patterns.

Python Solution:
def star_triangle(n):
for i in range(1, n+1):
print('*' * i)

def numeric_triangle(n):
for i in range(1, n+1):
print(''.join(str(j) for j in range(1, i+1)))

# Example (prints to stdout)


star_triangle(3)
numeric_triangle(3)
19. GCD and LCM

Problem: Compute GCD and LCM of two numbers.

Python Solution:
def gcd(a,b):
while b:
a, b = b, a % b
return abs(a)

def lcm(a,b):
if a == 0 or b == 0:
return 0
return abs(a // gcd(a,b) * b)

# Example
print(gcd(12,18)) # 6
print(lcm(12,18)) # 36

20. Power of a Number (fast exponentiation)

Problem: Compute a^b efficiently (integer b >= 0).

Python Solution:
def fast_pow(a, b):
res = 1
while b > 0:
if b & 1:
res *= a
a *= a
b >>= 1
return res

# Example
print(fast_pow(2,10)) # 1024

21. Perfect Number


Problem: Check if a number is perfect (sum of proper divisors equals n).

Python Solution:
def is_perfect(n):
if n <= 1:
return False
s = 1
i = 2
while i * i <= n:
if n % i == 0:
s += i
if i != n // i:
s += n // i
i += 1
return s == n

# Example
print(is_perfect(28)) # True

22. Count Passed Students (Scenario-based)

Problem: Given marks list and pass mark, count how many students passed.

Python Solution:
def count_passed(marks, pass_mark=40):
return sum(1 for m in marks if m >= pass_mark)

# Example
print(count_passed([55,30,90,42], 40)) # 3

23. Binary Search (sorted list) - basic

Problem: Classic binary search on sorted list to find target index or -1.

Python Solution:
def binary_search(arr, target):
lo, hi = 0, len(arr)-1
while lo <= hi:
mid = (lo + hi) // 2
if arr[mid] == target:
return mid
if arr[mid] < target:
lo = mid + 1
else:
hi = mid - 1
return -1

# Example
print(binary_search([1,3,5,7], 5)) # 2

24. Merge Two Sorted Lists (two-pointer)

Problem: Merge two sorted lists into one sorted list.

Python Solution:
def merge_sorted(a,b):
i = j = 0
res = []
while i < len(a) and j < len(b):
if a[i] <= b[j]:
[Link](a[i]); i += 1
else:
[Link](b[j]); j += 1
[Link](a[i:]); [Link](b[j:])
return res

# Example
print(merge_sorted([1,4,6],[2,3,5])) # [1,2,3,4,5,6]

25. Simple File I/O Example

Problem: Read integers from a file and print their sum (useful for competitive style input).

Python Solution:
def sum_from_file(path):
total = 0
with open(path) as f:
for line in f:
for token in [Link]():
try:
total += int(token)
except:
pass
return total

# Example: create a file '[Link]' and call sum_from_file('[Link]')


Tips for interview:
1. Practice writing code on paper or plain editor (no autocomplete).

2. Explain your approach before coding; interviewers value clarity of thought.

3. Start with a correct but simple solution, then improve if time permits.

4. Test edge cases (empty input, single element, large values).

5. Be familiar with one language's standard library (here: Python).

You might also like