š 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
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
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
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.
ā± O(n)
2ļøā£1ļøā£1ļøā£ Check if Two Arrays are Equal (Same Elements, Any Order)
š Compare sorted versions of both arrays.
ā± 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.
ā± O(n log n)
2ļøā£1ļøā£3ļøā£ Convert a Decimal Number to Binary
š Use Python's built-in
ā± 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.
ā± O(log n)
2ļøā£1ļøā£5ļøā£ Find the Common Elements Between Two Arrays (With Duplicates)
š Use Counter intersection to preserve duplicate counts.
ā± O(n+m)
2ļøā£1ļøā£6ļøā£ Check for Balanced Parentheses
š Use a stack to match opening and closing brackets.
ā± 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
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.
ā± O(n)
2ļøā£1ļøā£8ļøā£ Reverse a Linked List
š Iteratively reverse the
ā± O(n)
2ļøā£1ļøā£9ļøā£ Detect a Cycle in a Linked List
š Floyd's cycle detection ā if fast catches slow, there's a loop.
ā± O(n)
2ļøā£2ļøā£0ļøā£ Merge Two Sorted Linked Lists
š Compare nodes from both lists and link the smaller one each time.
ā± 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.
ā± O(n)
2ļøā£2ļøā£2ļøā£ Check if a Linked List is a Palindrome
š Reverse the second half and compare it with the first half.
ā± 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.
ā± 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
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.
ā± O(n)
2ļøā£2ļøā£5ļøā£ Perform an Inorder Traversal of a Binary Tree
š Visit left subtree, then root, then right subtree.
ā± O(n)
2ļøā£2ļøā£6ļøā£ Perform a Level Order Traversal (BFS) of a Binary Tree
š Use a queue to visit nodes level by level.
ā± 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.
ā± O(n)
2ļøā£2ļøā£8ļøā£ Find the Lowest Common Ancestor in a BST
š Traverse down; split point where paths diverge is the LCA.
ā± O(h)
2ļøā£2ļøā£9ļøā£ Check if Two Binary Trees are Identical
š Compare values and recursively check both subtrees.
ā± 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.
ā± 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
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
ā¤2
š 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.
ⱠO(n²)
2ļøā£3ļøā£2ļøā£ Implement Selection Sort
š Find the smallest element and place it at the correct position.
ⱠO(n²)
2ļøā£3ļøā£3ļøā£ Implement Insertion Sort
š Build the sorted array one element at a time.
ⱠO(n²)
2ļøā£3ļøā£4ļøā£ Implement Merge Sort
š Divide the array into smaller parts, sort them, and merge them.
ā± O(n log n)
2ļøā£3ļøā£5ļøā£ Implement Quick Sort
š Select a pivot and partition the array around it.
Ⱡ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.
ā± O(1) for push/pop
2ļøā£3ļøā£7ļøā£ Implement a Queue Using deque
š Add elements from the rear and remove them from the front.
ā± 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
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
āļø Java Interview Questions with Answers (Part 1)
1ļøā£ What is Java?
š Java is a high-level, object-oriented programming language designed to be portable across different platforms.
Key features:
š¹ Object-Oriented
š¹ Platform Independent
š¹ Secure
š¹ Robust
š¹ Multithreaded
š¹ Automatic Memory Management
š Write Once, Run Anywhere is commonly associated with Java's platform independence.
2ļøā£ What is JVM?
š JVM stands for Java Virtual Machine. It executes Java bytecode and provides the runtime environment required to run Java applications.
š Basic flow:
š” JVM implementations are platform-specific, which allows the same Java bytecode to run on different operating systems.
3ļøā£ What is the Difference Between JDK, JRE, and JVM?
š These three components have different roles:
š¹ JVM ā Executes Java bytecode
š¹ JRE ā JVM + libraries required to run Java applications
š¹ JDK ā JRE/runtime components + development tools such as the Java compiler
š JDK ā Development
š JRE ā Running applications
š JVM ā Executing bytecode
4ļøā£ What is a Class in Java?
š A class is a blueprint for creating objects. It defines data and behavior through fields, methods, constructors, and other members.
Example:
š” Objects are created from classes.
5ļøā£ What is an Object in Java?
š An object is an instance of a class. It contains state represented by fields and behavior provided by methods.
Example:
š Class ā Blueprint
š Object ā Instance of the class
š¬ Save this for your next Java interview preparation!
š„ Part 2 will cover 5 important questions on Inheritance, Polymorphism, Encapsulation, Abstraction & Constructors.
#Java #JavaInterview #JavaProgramming #Programming #OOP #CodingInterview #SoftwareEngineer #InterviewQuestions #Developer #TechInterview
1ļøā£ What is Java?
š Java is a high-level, object-oriented programming language designed to be portable across different platforms.
Key features:
š¹ Object-Oriented
š¹ Platform Independent
š¹ Secure
š¹ Robust
š¹ Multithreaded
š¹ Automatic Memory Management
š Write Once, Run Anywhere is commonly associated with Java's platform independence.
2ļøā£ What is JVM?
š JVM stands for Java Virtual Machine. It executes Java bytecode and provides the runtime environment required to run Java applications.
š Basic flow:
Java Source Code
ā
Compiler
ā
Bytecode
ā
JVM
ā
Output
š” JVM implementations are platform-specific, which allows the same Java bytecode to run on different operating systems.
3ļøā£ What is the Difference Between JDK, JRE, and JVM?
š These three components have different roles:
š¹ JVM ā Executes Java bytecode
š¹ JRE ā JVM + libraries required to run Java applications
š¹ JDK ā JRE/runtime components + development tools such as the Java compiler
š JDK ā Development
š JRE ā Running applications
š JVM ā Executing bytecode
4ļøā£ What is a Class in Java?
š A class is a blueprint for creating objects. It defines data and behavior through fields, methods, constructors, and other members.
Example:
class Student {
String name;
int age;
void display() {
System.out.println(name + " " + age);
}
}š” Objects are created from classes.
5ļøā£ What is an Object in Java?
š An object is an instance of a class. It contains state represented by fields and behavior provided by methods.
Example:
class Student {
String name;
void display() {
System.out.println(name);
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student();
s.name = "Rahul";
s.display();
}
}š Class ā Blueprint
š Object ā Instance of the class
š¬ Save this for your next Java interview preparation!
š„ Part 2 will cover 5 important questions on Inheritance, Polymorphism, Encapsulation, Abstraction & Constructors.
#Java #JavaInterview #JavaProgramming #Programming #OOP #CodingInterview #SoftwareEngineer #InterviewQuestions #Developer #TechInterview
āļø Java Interview Questions with Answers (Part 2)
6ļøā£ What is Inheritance in Java?
š Inheritance allows a class to acquire fields and methods from another class. It helps create reusable and hierarchical code.
Example:
š
7ļøā£ What is Polymorphism in Java?
š Polymorphism means one interface or method name can represent different behaviors.
Two common forms are:
š¹ Compile-time Polymorphism ā Method Overloading
š¹ Runtime Polymorphism ā Method Overriding
Example of Overloading:
š” The same method name
8ļøā£ What is Encapsulation in Java?
š Encapsulation means bundling data and methods together while controlling direct access to the data.
Example:
š
š” Encapsulation helps protect object state and provides controlled access.
9ļøā£ What is Abstraction in Java?
š Abstraction means hiding implementation details and exposing only the essential functionality.
Java supports abstraction using:
š¹ Abstract Classes
š¹ Interfaces
Example:
š” The user of
š What is a Constructor in Java?
š A constructor is a special member used to initialize an object when it is created.
Example:
š Constructor name must match the class name.
š” Constructors do not have a return type, including
š¬ Save this for your Java interview preparation!
š„ Part 3 will cover 5 important questions on Method Overloading, Method Overriding,
#Java #JavaInterview #JavaProgramming #OOP #CodingInterview #Programming #SoftwareEngineer #InterviewQuestions #Developer #TechInterview
6ļøā£ What is Inheritance in Java?
š Inheritance allows a class to acquire fields and methods from another class. It helps create reusable and hierarchical code.
Example:
class Animal {
void eat() {
System.out.println("Eating");
}
}
class Dog extends Animal {
void bark() {
System.out.println("Barking");
}
}
public class Main {
public static void main(String[] args) {
Dog d = new Dog();
d.eat();
d.bark();
}
}š
Dog inherits the eat() method from Animal.7ļøā£ What is Polymorphism in Java?
š Polymorphism means one interface or method name can represent different behaviors.
Two common forms are:
š¹ Compile-time Polymorphism ā Method Overloading
š¹ Runtime Polymorphism ā Method Overriding
Example of Overloading:
class Calculator {
int add(int a, int b) {
return a + b;
}
int add(int a, int b, int c) {
return a + b + c;
}
}š” The same method name
add() works with different parameter lists.8ļøā£ What is Encapsulation in Java?
š Encapsulation means bundling data and methods together while controlling direct access to the data.
Example:
class Student {
private int age;
public void setAge(int age) {
this.age = age;
}
public int getAge() {
return age;
}
}š
private prevents direct access from outside the class.š” Encapsulation helps protect object state and provides controlled access.
9ļøā£ What is Abstraction in Java?
š Abstraction means hiding implementation details and exposing only the essential functionality.
Java supports abstraction using:
š¹ Abstract Classes
š¹ Interfaces
Example:
abstract class Animal {
abstract void sound();
void sleep() {
System.out.println("Sleeping");
}
}
class Dog extends Animal {
void sound() {
System.out.println("Bark");
}
}š” The user of
Animal does not need to know how sound() is implemented internally.š What is a Constructor in Java?
š A constructor is a special member used to initialize an object when it is created.
Example:
class Student {
String name;
Student(String name) {
this.name = name;
}
void display() {
System.out.println(name);
}
}
public class Main {
public static void main(String[] args) {
Student s = new Student("Rahul");
s.display();
}
}š Constructor name must match the class name.
š” Constructors do not have a return type, including
void.š¬ Save this for your Java interview preparation!
š„ Part 3 will cover 5 important questions on Method Overloading, Method Overriding,
this, super & static.#Java #JavaInterview #JavaProgramming #OOP #CodingInterview #Programming #SoftwareEngineer #InterviewQuestions #Developer #TechInterview
āļø Java Interview Questions with Answers (Part 3)
1ļøā£1ļøā£ What is Method Overloading in Java?
š Method Overloading means having multiple methods with the same name but different parameter lists in the same class.
š” Overloading is resolved at compile time.
1ļøā£2ļøā£ What is Method Overriding in Java?
š Method Overriding occurs when a subclass provides its own implementation of an inherited method.
š” Overriding is associated with runtime polymorphism.
1ļøā£3ļøā£ What is the
š
It is commonly used to:
š¹ Access current object's fields
š¹ Call current class methods
š¹ Invoke another constructor
Example:
1ļøā£4ļøā£ What is the
š
It can be used to:
š¹ Access parent fields
š¹ Call parent methods
š¹ Call the parent constructor
Example:
š Output:
1ļøā£5ļøā£ What is the
š
Example:
š Output:
š” A static field is shared among instances of the class.
š¬ Save this for your Java interview preparation!
š„ Next: Python Interview Questions ā Part 2
#Java #JavaInterview #JavaProgramming #OOP #CodingInterview #Programming #InterviewQuestions #Developer #SoftwareEngineer
1ļøā£1ļøā£ What is Method Overloading in Java?
š Method Overloading means having multiple methods with the same name but different parameter lists in the same class.
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}š” Overloading is resolved at compile time.
1ļøā£2ļøā£ What is Method Overriding in Java?
š Method Overriding occurs when a subclass provides its own implementation of an inherited method.
class Animal {
void sound() {
System.out.println("Animal sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Bark");
}
}š” Overriding is associated with runtime polymorphism.
1ļøā£3ļøā£ What is the
this Keyword in Java?š
this refers to the current object.It is commonly used to:
š¹ Access current object's fields
š¹ Call current class methods
š¹ Invoke another constructor
Example:
class Student {
String name;
Student(String name) {
this.name = name;
}
}1ļøā£4ļøā£ What is the
super Keyword in Java?š
super refers to the immediate parent class.It can be used to:
š¹ Access parent fields
š¹ Call parent methods
š¹ Call the parent constructor
Example:
class Animal {
String name = "Animal";
}
class Dog extends Animal {
String name = "Dog";
void display() {
System.out.println(super.name);
}
}š Output:
Animal
1ļøā£5ļøā£ What is the
static Keyword in Java?š
static indicates that a member belongs to the class rather than a particular object.Example:
class Counter {
static int count = 0;
Counter() {
count++;
}
}
public class Main {
public static void main(String[] args) {
new Counter();
new Counter();
System.out.println(Counter.count);
}
}š Output:
2
š” A static field is shared among instances of the class.
š¬ Save this for your Java interview preparation!
š„ Next: Python Interview Questions ā Part 2
#Java #JavaInterview #JavaProgramming #OOP #CodingInterview #Programming #InterviewQuestions #Developer #SoftwareEngineer