ProjectWithSourceCodes
1.03K subscribers
293 photos
8 videos
43 files
1.35K links
Free Source Code Projects for Students 🚀 | Python | Java | Android | Web Dev | AI/ML | Final Year Projects | BCA • BTech • MCA | Interview Prep | Job Alerts

Website: https://updategadh.com
Download Telegram
🚀 Coding Interview Questions with Answers (Part :-1)

1️⃣8️⃣9️⃣ Check if Two Strings are Anagrams
👉 Same characters, same frequency, different order.

python
s1, s2 = "listen", "silent"
print(sorted(s1) == sorted(s2))

O(n log n)

1️⃣9️⃣0️⃣ Factorial of a Number
👉 Product of all integers from 1 to n.

python
def factorial(n):
result = 1
for i in range(1, n+1):
result *= i
return result

O(n)

1️⃣9️⃣1️⃣ Check if a Number is Prime
👉 Divisible only by 1 and itself.

python
def is_prime(n):
if n < 2: return False
for i in range(2, int(n**0.5)+1):
if n % i == 0: return False
return True

O(√n)

1️⃣9️⃣2️⃣ Fibonacci Sequence
👉 Sum of the two preceding numbers.

python
def fibonacci(n):
seq = [0, 1]
while len(seq) < n:
seq.append(seq[-1]+seq[-2])
return seq[:n]

O(n)

1️⃣9️⃣3️⃣ GCD of Two Numbers
👉 Euclidean algorithm.

python
def gcd(a, b):
while b:
a, b = b, a % b
return a

O(log(min(a,b)))

1️⃣9️⃣4️⃣ Frequency of Elements
👉 Count occurrences using Counter.

python
from collections import Counter
print(Counter([1,2,2,3,3,3]))

O(n)

1️⃣9️⃣5️⃣ Rotate Array by K Positions
👉 Slice and swap.

python
def rotate(arr, k):
k = k % len(arr)
return arr[-k:] + arr[:-k]

O(n)

💬 Save this for your next interview prep! Which topic should Part 2 cover — Linked Lists, Trees, or Sorting Algorithms? 👇

#coding #interview #python #programming #softwareengineer #dsa
🚀 Coding Interview Questions with Answers (Part:-2)

1️⃣9️⃣6️⃣ Find All Pairs with a Given Sum
👉 Use a set to track complements while scanning.

python
def find_pairs(arr, target):
seen, pairs = set(), []
for num in arr:
complement = target - num
if complement in seen:
pairs.append((complement, num))
seen.add(num)
return pairs

print(find_pairs([2,4,3,7,1,5], 7))

O(n)

1️⃣9️⃣7️⃣ Check if an Array is Sorted
👉 Compare each element with the next one.

python
def is_sorted(arr):
return all(arr[i] <= arr[i+1] for i in range(len(arr)-1))

print(is_sorted([1,2,3,4,5]))

O(n)

1️⃣9️⃣8️⃣ Find the Intersection of Two Arrays
👉 Use set intersection to find common elements.

python
a = [1,2,3,4]
b = [3,4,5,6]
print(list(set(a) & set(b)))

O(n+m)

1️⃣9️⃣9️⃣ Count Vowels in a String
👉 Loop through and check membership in a vowel set.

python
def count_vowels(s):
return sum(1 for ch in s.lower() if ch in "aeiou")

print(count_vowels("Hello World"))

O(n)

2️⃣0️⃣0️⃣ Check if a Number is a Power of Two
👉 A power of two has exactly one bit set — use bitwise AND trick.

python
def is_power_of_two(n):
return n > 0 and (n & (n-1)) == 0

print(is_power_of_two(16))

O(1)

2️⃣0️⃣1️⃣ Flatten a Nested List
👉 Recursively unpack nested lists into a single flat list.

python
def flatten(lst):
result = []
for item in lst:
if isinstance(item, list):
result.extend(flatten(item))
else:
result.append(item)
return result

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

O(n)

2️⃣0️⃣2️⃣ Find the First Non-Repeating Character
👉 Use a frequency count, then find the first with count 1.

python
from collections import Counter

def first_unique(s):
freq = Counter(s)
for ch in s:
if freq[ch] == 1:
return ch
return None

print(first_unique("swiss"))

O(n)

💬 Bookmark this for your next interview prep! Should Part 3 dive into Linked Lists, Binary Trees, or Sorting Algorithms? 👇

#coding #interview #python #programming #softwareengineer #dsa
🚀 Coding Interview Questions with Answers (Part 3)

2️⃣0️⃣3️⃣ Find the Union of Two Arrays
👉 Combine both arrays and remove duplicates.

python
a = [1,2,3,4]
b = [3,4,5,6]
print(list(set(a) | set(b)))

O(n+m)

2️⃣0️⃣4️⃣ Check if a String Contains Only Digits
👉 Use the built-in isdigit() method.

python
s = "12345"
print(s.isdigit())

O(n)

2️⃣0️⃣5️⃣ Find the Sum of Digits of a Number
👉 Repeatedly extract the last digit and add it up.

python
def sum_of_digits(n):
total = 0
while n > 0:
total += n % 10
n //= 10
return total

print(sum_of_digits(12345))

O(log n)

2️⃣0️⃣6️⃣ Reverse an Integer
👉 Convert to string, reverse, convert back — or use math.

python
def reverse_int(n):
sign = -1 if n < 0 else 1
n = abs(n)
reversed_num = int(str(n)[::-1])
return sign * reversed_num

print(reverse_int(-12345))

O(log n)

2️⃣0️⃣7️⃣ Check if a String is a Subsequence of Another
👉 Use two pointers to compare characters in order.

python
def is_subsequence(s, t):
it = iter(t)
return all(ch in it for ch in s)

print(is_subsequence("abc", "ahbgdc"))

O(n)

2️⃣0️⃣8️⃣ Find the Maximum Product of Two Numbers in an Array
👉 Sort and multiply the two largest values.

python
def max_product(arr):
arr.sort()
return arr[-1] * arr[-2]

print(max_product([1,5,3,9,2]))

O(n log n)

2️⃣0️⃣9️⃣ Find All Permutations of a String
👉 Use recursion or the itertools.permutations function.

python
from itertools import permutations

s = "abc"
perms = ["".join(p) for p in permutations(s)]
print(perms)

O(n!)

💬 Save this for your next interview prep! Should Part 4 cover Linked Lists, Binary Trees, or Sorting Algorithms? 👇

#coding #interview #python #programming #softwareengineer #dsa
🚀 Coding Interview Questions with Answers (Part 4)

2️⃣1️⃣0️⃣ Find the Longest Word in a String
👉 Split the string into words and track the longest one.
def longest_word(s):
words = s.split()
return max(words, key=len)

print(longest_word("The quick brown fox jumped"))

O(n)

2️⃣1️⃣1️⃣ Check if Two Arrays are Equal (Same Elements, Any Order)
👉 Compare sorted versions of both arrays.
a = [1,2,3]
b = [3,2,1]
print(sorted(a) == sorted(b))

O(n log n)

2️⃣1️⃣2️⃣ Find the Kth Largest Element in an Array
👉 Sort the array and pick the element at index -k.
def kth_largest(arr, k):
return sorted(arr)[-k]

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

O(n log n)

2️⃣1️⃣3️⃣ Convert a Decimal Number to Binary
👉 Use Python's built-in bin() function.
n = 42
print(bin(n)[2:])

O(log n)

2️⃣1️⃣4️⃣ Check if a Number is an Armstrong Number
👉 Sum of each digit raised to the power of digit count equals the number.
def is_armstrong(n):
digits = str(n)
power = len(digits)
return n == sum(int(d)**power for d in digits)

print(is_armstrong(153))

O(log n)

2️⃣1️⃣5️⃣ Find the Common Elements Between Two Arrays (With Duplicates)
👉 Use Counter intersection to preserve duplicate counts.
from collections import Counter

a = [1,2,2,3]
b = [2,2,3,4]
common = list((Counter(a) & Counter(b)).elements())
print(common)

O(n+m)

2️⃣1️⃣6️⃣ Check for Balanced Parentheses
👉 Use a stack to match opening and closing brackets.
def is_balanced(s):
stack = []
pairs = {')':'(', ']':'[', '}':'{'}
for ch in s:
if ch in "([{":
stack.append(ch)
elif ch in ")]}":
if not stack or stack.pop() != pairs[ch]:
return False
return not stack

print(is_balanced("{[()]}"))

O(n)

💬 Save this for your next interview prep! Should Part 5 cover Linked Lists, Binary Trees, or Sorting Algorithms? 👇

#coding #interview #python #programming #softwareengineer #dsa
🚀 Coding Interview Questions with Answers (Part 5)

2️⃣1️⃣7️⃣ Find the Middle Element of a Linked List
👉 Use the slow-fast pointer technique — fast moves 2x speed of slow.
class Node:
def __init__(self, data):
self.data = data
self.next = None

def find_middle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow.data

O(n)

2️⃣1️⃣8️⃣ Reverse a Linked List
👉 Iteratively reverse the next pointer of each node.
def reverse_list(head):
prev = None
curr = head
while curr:
nxt = curr.next
curr.next = prev
prev = curr
curr = nxt
return prev

O(n)

2️⃣1️⃣9️⃣ Detect a Cycle in a Linked List
👉 Floyd's cycle detection — if fast catches slow, there's a loop.
def has_cycle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow == fast:
return True
return False

O(n)

2️⃣2️⃣0️⃣ Merge Two Sorted Linked Lists
👉 Compare nodes from both lists and link the smaller one each time.
def merge_lists(l1, l2):
dummy = Node(0)
tail = dummy
while l1 and l2:
if l1.data < l2.data:
tail.next, l1 = l1, l1.next
else:
tail.next, l2 = l2, l2.next
tail = tail.next
tail.next = l1 or l2
return dummy.next

O(n+m)

2️⃣2️⃣1️⃣ Remove the Nth Node from the End of a Linked List
👉 Use two pointers with a gap of n between them.
def remove_nth_from_end(head, n):
dummy = Node(0)
dummy.next = head
fast = slow = dummy
for _ in range(n):
fast = fast.next
while fast.next:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return dummy.next

O(n)

2️⃣2️⃣2️⃣ Check if a Linked List is a Palindrome
👉 Reverse the second half and compare it with the first half.
def is_palindrome(head):
vals = []
while head:
vals.append(head.data)
head = head.next
return vals == vals[::-1]

O(n)

2️⃣2️⃣3️⃣ Find the Intersection Point of Two Linked Lists
👉 Traverse both lists, switching heads when reaching the end, so paths align.
def get_intersection(headA, headB):
a, b = headA, headB
while a != b:
a = a.next if a else headB
b = b.next if b else headA
return a

O(n+m)

💬 Save this for your next interview prep! Should Part 6 cover Binary Trees, Sorting Algorithms, or Stacks & Queues? 👇

#coding #interview #python #programming #softwareengineer #dsa
🚀 Coding Interview Questions with Answers (Part 6)

2️⃣2️⃣4️⃣ Find the Height of a Binary Tree
👉 Recursively find the max depth of left and right subtrees.
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None

def tree_height(root):
if not root:
return 0
return 1 + max(tree_height(root.left), tree_height(root.right))

O(n)

2️⃣2️⃣5️⃣ Perform an Inorder Traversal of a Binary Tree
👉 Visit left subtree, then root, then right subtree.
def inorder(root, result=None):
if result is None:
result = []
if root:
inorder(root.left, result)
result.append(root.data)
inorder(root.right, result)
return result

O(n)

2️⃣2️⃣6️⃣ Perform a Level Order Traversal (BFS) of a Binary Tree
👉 Use a queue to visit nodes level by level.
from collections import deque

def level_order(root):
result = []
queue = deque([root])
while queue:
node = queue.popleft()
if node:
result.append(node.data)
queue.append(node.left)
queue.append(node.right)
return result

O(n)

2️⃣2️⃣7️⃣ Check if a Binary Tree is a Valid BST
👉 Recursively verify each node falls within a valid min/max range.
def is_valid_bst(root, low=float('-inf'), high=float('inf')):
if not root:
return True
if not (low < root.data < high):
return False
return (is_valid_bst(root.left, low, root.data) and
is_valid_bst(root.right, root.data, high))

O(n)

2️⃣2️⃣8️⃣ Find the Lowest Common Ancestor in a BST
👉 Traverse down; split point where paths diverge is the LCA.
def lowest_common_ancestor(root, p, q):
while root:
if p < root.data and q < root.data:
root = root.left
elif p > root.data and q > root.data:
root = root.right
else:
return root.data

O(h)

2️⃣2️⃣9️⃣ Check if Two Binary Trees are Identical
👉 Compare values and recursively check both subtrees.
def is_identical(t1, t2):
if not t1 and not t2:
return True
if not t1 or not t2:
return False
return (t1.data == t2.data and
is_identical(t1.left, t2.left) and
is_identical(t1.right, t2.right))

O(n)

2️⃣3️⃣0️⃣ Find the Diameter of a Binary Tree
👉 The longest path between any two nodes — may or may not pass through root.
def diameter(root):
result = [0]
def depth(node):
if not node:
return 0
left = depth(node.left)
right = depth(node.right)
result[0] = max(result[0], left + right)
return 1 + max(left, right)
depth(root)
return result[0]

O(n)

💬 Save this for your next interview prep! Should Part 7 cover Sorting Algorithms, Stacks & Queues, or Graphs? 👇

#coding #interview #python #programming #softwareengineer #dsa
1
🚀 Coding Interview Questions with Answers (Part 7)

2️⃣3️⃣1️⃣ Implement Bubble Sort
👉 Repeatedly compare adjacent elements and swap them if they are in the wrong order.

def bubble_sort(arr):
n = len(arr)
for i in range(n):
for j in range(0, n - i - 1):
if arr[j] > arr[j + 1]:
arr[j], arr[j + 1] = arr[j + 1], arr[j]
return arr


O(n²)

2️⃣3️⃣2️⃣ Implement Selection Sort
👉 Find the smallest element and place it at the correct position.

def selection_sort(arr):
n = len(arr)
for i in range(n):
min_index = i
for j in range(i + 1, n):
if arr[j] < arr[min_index]:
min_index = j
arr[i], arr[min_index] = arr[min_index], arr[i]
return arr


O(n²)

2️⃣3️⃣3️⃣ Implement Insertion Sort
👉 Build the sorted array one element at a time.

def insertion_sort(arr):
for i in range(1, len(arr)):
key = arr[i]
j = i - 1

while j >= 0 and arr[j] > key:
arr[j + 1] = arr[j]
j -= 1

arr[j + 1] = key

return arr


O(n²)

2️⃣3️⃣4️⃣ Implement Merge Sort
👉 Divide the array into smaller parts, sort them, and merge them.

def merge_sort(arr):
if len(arr) <= 1:
return arr

mid = len(arr) // 2
left = merge_sort(arr[:mid])
right = merge_sort(arr[mid:])

result = []
i = j = 0

while i < len(left) and j < len(right):
if left[i] < right[j]:
result.append(left[i])
i += 1
else:
result.append(right[j])
j += 1

result.extend(left[i:])
result.extend(right[j:])

return result


O(n log n)

2️⃣3️⃣5️⃣ Implement Quick Sort
👉 Select a pivot and partition the array around it.

def quick_sort(arr):
if len(arr) <= 1:
return arr

pivot = arr[-1]
left = [x for x in arr[:-1] if x <= pivot]
right = [x for x in arr[:-1] if x > pivot]

return quick_sort(left) + [pivot] + quick_sort(right)


Average O(n log n) | Worst O(n²)

2️⃣3️⃣6️⃣ Implement a Stack Using a List
👉 Use the end of the list for efficient push and pop operations.

class Stack:
def __init__(self):
self.items = []

def push(self, item):
self.items.append(item)

def pop(self):
if self.items:
return self.items.pop()
return None

def peek(self):
return self.items[-1] if self.items else None


O(1) for push/pop

2️⃣3️⃣7️⃣ Implement a Queue Using deque
👉 Add elements from the rear and remove them from the front.

from collections import deque

class Queue:
def __init__(self):
self.items = deque()

def enqueue(self, item):
self.items.append(item)

def dequeue(self):
if self.items:
return self.items.popleft()
return None


O(1) for enqueue/dequeue

💬 Save this for your next interview prep!

🔥 Should Part 8 cover Graphs, Dynamic Programming, or Recursion & Backtracking? 👇

#coding #interview #python #programming #softwareengineer #dsa