Top 20 Coding Questions and Answers for Cognizant & TCS Campus
Recruitment (2025 Batch - Freshers)
1. Reverse a String
Input: "hello"
Output: "olleh"
Python:
s = "hello"
print(s[::-1])
2. Check Palindrome String
Input: "madam"
Output: Yes
Python:
s = "madam"
print("Yes" if s == s[::-1] else "No")
3. Fibonacci Series up to N
Input: 5
Output: 0 1 1 2 3
Python:
n=5
a, b = 0, 1
for _ in range(n):
print(a, end=' ')
a, b = b, a + b
4. Prime Number Check
Input: 7
Output: Prime
Python:
n=7
is_prime = all(n % i != 0 for i in range(2, int(n**0.5)+1))
print("Prime" if is_prime and n > 1 else "Not Prime")
5. Factorial Using Recursion
Input: 5
Output: 120
Python:
def fact(n):
return 1 if n==0 else n*fact(n-1)
print(fact(5))
6. Find Max in Array
Input: [1, 9, 3]
Output: 9
Python:
arr = [1, 9, 3]
print(max(arr))
7. Print Diamond Pattern
Input: 3
Output:
***
*****
***
Python:
n=3
for i in range(n):
print(" "*(n-i-1) + "*"*(2*i+1))
for i in range(n-2, -1, -1):
print(" "*(n-i-1) + "*"*(2*i+1))
8. Anagram Check
Input: "listen", "silent"
Output: Anagram
Python:
s1 = "listen"
s2 = "silent"
print("Anagram" if sorted(s1)==sorted(s2) else "Not Anagram")
9. Second Largest in Array
Input: [2, 3, 1, 4]
Output: 3
Python:
arr = [2, 3, 1, 4]
arr = list(set(arr))
arr.sort()
print(arr[-2])
10. FizzBuzz
Print numbers 1 to 15. For multiples of 3 print "Fizz", 5 print "Buzz", both 3 and 5 print "FizzBuzz".
Python:
for i in range(1, 16):
if i % 3 == 0 and i % 5 == 0:
print("FizzBuzz")
elif i % 3 == 0:
print("Fizz")
elif i % 5 == 0:
print("Buzz")
else:
print(i)
11. Count Vowels in a String
Input: "education"
Output: 5
Python:
s = "education"
vowels = "aeiouAEIOU"
print(sum(1 for ch in s if ch in vowels))
12. Sum of Digits
Input: 1234
Output: 10
Python:
n = 1234
print(sum(int(d) for d in str(n)))
13. Remove Duplicates from Array
Input: [1, 2, 2, 3]
Output: [1, 2, 3]
Python:
arr = [1, 2, 2, 3]
print(list(set(arr)))
14. GCD of Two Numbers
Input: 12, 18
Output: 6
Python:
import math
print(math.gcd(12, 18))
15. Find Missing Number in Sequence
Input: [1, 2, 4, 5]
Output: 3
Python:
arr = [1, 2, 4, 5]
n=5
print(n*(n+1)//2 - sum(arr))
16. Count Frequency of Elements
Input: [1, 2, 2, 3]
Output: {1:1, 2:2, 3:1}
Python:
from collections import Counter
print(dict(Counter([1, 2, 2, 3])))
17. Binary Search (on sorted list)
Input: arr=[1,2,3,4,5], target=4
Output: Index 3
Python:
def binary_search(arr, target):
low, high = 0, len(arr)-1
while low <= high:
mid = (low + high)//2
if arr[mid] == target:
return mid
elif arr[mid] < target:
low = mid + 1
else:
high = mid - 1
return -1
print(binary_search([1,2,3,4,5], 4))
18. Check Armstrong Number
Input: 153
Output: Yes
Python:
n = 153
total = sum(int(d)**3 for d in str(n))
print("Yes" if total == n else "No")
19. Convert Decimal to Binary
Input: 10
Output: 1010
Python:
print(bin(10)[2:])
20. Merge Two Sorted Arrays
Input: [1,3,5], [2,4,6]
Output: [1,2,3,4,5,6]
Python:
arr1 = [1,3,5]
arr2 = [2,4,6]
print(sorted(arr1 + arr2))