KEMBAR78
Placement 50 Python Solutions | PDF | Computer Programming | Algorithms And Data Structures
0% found this document useful (0 votes)
15 views11 pages

Placement 50 Python Solutions

The document contains 50 common coding questions with concise Python solutions, covering a variety of topics such as number manipulation, string processing, data structures, and algorithms. Each question includes an example of usage to illustrate the solution. The solutions are designed to be runnable and provide a practical approach to common coding challenges.

Uploaded by

navin.verma262
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views11 pages

Placement 50 Python Solutions

The document contains 50 common coding questions with concise Python solutions, covering a variety of topics such as number manipulation, string processing, data structures, and algorithms. Each question includes an example of usage to illustrate the solution. The solutions are designed to be runnable and provide a practical approach to common coding challenges.

Uploaded by

navin.verma262
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

50 Common Placement Coding Questions — Python

Solutions
Each question includes a concise, runnable Python solution. Examples are provided where
helpful.

1. Reverse a number
def reverse_number(n):
sign = -1 if n < 0 else 1
n = abs(n)
rev = 0
while n:
rev = rev*10 + n%10
n //= 10
return sign*rev

# example
print(reverse_number(12345)) #
54321

2. Check if a number is palindrome


def is_palindrome_num(n):
return n == int(str(n)[::-1])

print(is_palindrome_num(121)) # True

3. Factorial of n (iterative)
def factorial(n):
if n < 0: raise ValueError("n must be >=0")
res = 1
for i in range(2,
n+1):
res *= i
return res

print(factorial(5)) # 120

4. Fibonacci series up to n (iterative)


def fibonacci(n):
a, b = 0, 1
seq = []
while a <= n:
seq.append(a)
a, b
= b, a+b
return seq

print(fibonacci(21))

5. Sum of digits of a number


def sum_of_digits(n):
return sum(int(d) for d in str(abs(n)))

print(sum_of_digits(1234)) # 10
6. Power of a number (a^b) - fast exponentiation
def power(a, b):
res = 1
base = a
exp = b
while exp > 0:
if exp & 1:
res *= base
base *= base
exp >>= 1
return res

print(power(2, 10)) # 1024

7. Reverse an array/list
def reverse_list(arr):
return arr[::-1]

print(reverse_list([1,2,3,4])) # [4,3,2,1]

8. Reverse a string
def reverse_string(s):
return s[::-1]

print(reverse_string('hello')) # 'olleh'

9. Check if a string is palindrome


def is_palindrome(s):
s2 = ''.join(ch.lower() for ch in s if ch.isalnum())
return s2 ==
s2[::-1]

print(is_palindrome('A man, a plan, a canal: Panama')) # True

10. Check anagram of two strings


from collections import Counter
def are_anagrams(a, b):
return Counter(a.replace('
','').lower()) == Counter(b.replace(' ','').lower())

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

11. Count vowels in a string


def count_vowels(s):
return sum(1 for ch in s.lower() if ch in 'aeiou')
print(count_vowels('hello world')) # 3

12. Check prime number (simple)


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

print(is_prime(29)) # True

13. Sieve of Eratosthenes - primes up to n


def sieve(n):
if n < 2: return []
is_prime = [True]*(n+1)
is_prime[0:2] = [False, False]
p = 2
while p*p <= n:
if is_prime[p]:
for multiple in range(p*p, n+1, p):
is_prime[multiple] = False
p += 1
return [i for i, val in enumerate(is_prime) if val]
print(sieve(30))

14. GCD (Euclidean algorithm)


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

print(gcd(48, 18)) # 6

15. LCM using GCD


def lcm(a, b):
return abs(a//gcd(a,b)*b) if a and b else 0

print(lcm(12, 18)) # 36

16. Swap two numbers without temp (Pythonic)


a, b = 5, 10
a, b = b, a
print(a, b) # 10 5

17. Check if number is power of two


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

print(is_power_of_two(16)) # True

18. Remove duplicates from list (preserve order)


def remove_duplicates(arr):
seen = set()
out = []
for x in arr:
if x not in
seen:
seen.add(x)
out.append(x)
return out
print(remove_duplicates([1,2,2,3,1])) # [1,2,3]

19. Find duplicate elements (all)


from collections import Counter
def find_duplicates(arr):
return [x for x, c in
Counter(arr).items() if c > 1]

print(find_duplicates([1,2,2,3,3,4])) # [2,3]

20. Two-sum (find indices) - hashmap method


def two_sum(nums, target):
seen = {}
for i, v in enumerate(nums):
if target - v in
seen:
return (seen[target-v], i)
seen[v] = i
return None
print(two_sum([2,7,11,15], 9)) # (0,1)

21. Pair with given sum in sorted array - two pointers


def pair_sum_sorted(arr, target):
i, j = 0, len(arr)-1
while i < j:
s = arr[i] +
arr[j]
if s == target: return (i, j)
if s < target: i += 1
else: j -= 1
return None

print(pair_sum_sorted([1,2,3,4,5], 9)) # (3,4)

22. Find kth largest using heapq


import heapq
def kth_largest(nums, k):
return heapq.nlargest(k, nums)[-1]
print(kth_largest([3,2,1,5,6,4], 2)) # 5

23. Majority element (Boyer-Moore)


def majority_element(nums):
count = 0; candidate = None
for num in nums:
if count ==
0: candidate = num
count += (1 if num == candidate else -1)
return candidate
print(majority_element([2,2,1,2,1,2])) # 2
24. Move zeros to end (in-place)
def move_zeros(arr):
j = 0
for i in range(len(arr)):
if arr[i] != 0:
arr[j] = arr[i]
j += 1
for k in range(j, len(arr)):
arr[k] = 0
return
arr

print(move_zeros([0,1,0,3,12])) # [1,3,12,0,0]

25. Merge two sorted arrays (result)


def merge_sorted(a, b):
i = j = 0; out = []
while i < len(a) and j < len(b):
if a[i]
< b[j]:
out.append(a[i]); i += 1
else:
out.append(b[j]); j += 1
out.extend(a[i:]); out.extend(b[j:])
return out

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

26. Longest common prefix (strings)


def longest_common_prefix(strs):
if not strs: return ''
strs.sort()
a, b = strs[0],
strs[-1]
i = 0
while i < min(len(a), len(b)) and a[i]==b[i]:
i += 1
return a[:i]
print(longest_common_prefix(['flower','flow','flight'])) # 'fl'

27. Binary search (iterative)


def binary_search(arr, target):
l, r = 0, len(arr)-1
while l <= r:
m = (l+r)//2
if arr[m] == target: return m
if arr[m] < target: l = m+1
else: r = m-1
return
-1

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

28. Check if two strings are rotations of each other


def is_rotation(a, b):
return len(a)==len(b) and b in (a+a)
print(is_rotation('abcd','cdab'))
# True

29. Count set bits in an integer


def count_set_bits(n):
count = 0
while n:
n &= n-1
count += 1
return
count

print(count_set_bits(29)) # 4

30. Implement stack with basic ops


class Stack:
def init (self): self._ = []
def push(self, x): self._ .append(x)
def
pop(self): return self._ .pop() if self._ else None
def peek(self): return self._[-1] if self._
else None
def is_empty(self): return len(self._)==0

s = Stack(); s.push(1); s.push(2);


print(s.pop()) # 2

31. Implement queue using collections.deque


from collections import deque
class Queue:
def init (self): self.q = deque()
def
enqueue(self, x): self.q.append(x)
def dequeue(self): return self.q.popleft() if self.q else
None

q = Queue(); q.enqueue(1); q.enqueue(2); print(q.dequeue()) # 1

32. Reverse linked list (iterative) - singly linked list nodes


class Node:
def init (self, val): self.val = val; self.next = None

def reverse_list(head):
prev = None
cur = head
while cur:
nxt = cur.next
cur.next = prev
prev = cur
cur = nxt
return prev

# Create 1->2->3
h = Node(1); h.next = Node(2);
h.next.next = Node(3)
r = reverse_list(h)
print(r.val, r.next.val, r.next.next.val) # 3 2 1
33. Detect cycle in linked list (Floyd's)
def has_cycle(head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast: return True
return False

# (Use Node from prev


example)

34. Find middle of linked list


def middle_node(head):
slow = fast = head
while fast and fast.next:
slow =
slow.next; fast = fast.next.next
return slow

35. Merge two sorted linked lists


def merge_two_lists(a, b):
dummy = Node(0)
tail = dummy
while a and b:
if a.val
< b.val:
tail.next = a; a = a.next
else:
tail.next = b; b = b.next
tail = tail.next
tail.next = a or b
return dummy.next

36. Validate parentheses (stack)


def is_valid(s):
stack = []
mapping = {')':'(', ']':'[', '}':'{'}
for ch in s:
if ch in mapping.values(): stack.append(ch)
elif ch in mapping:
if not stack or
stack.pop() != mapping[ch]: return False
return not stack

print(is_valid('()[]{}')) # True

37. Inorder traversal of binary tree (recursive)


class TreeNode:
def init (self, val): self.val = val; self.left = self.right = None

def
inorder(root):
return inorder(root.left) + [root.val] + inorder(root.right) if root else []

#
Example tree 1-2-3 as root.left=2, root.right=3
38. Level order traversal (BFS)
from collections import deque
def level_order(root):
if not root: return []
q =
deque([root]); out = []
while q:
node = q.popleft()
out.append(node.val)
if node.left: q.append(node.left)
if node.right: q.append(node.right)
return out

39. Check balanced parentheses string length of longest valid parentheses


def longest_valid_parentheses(s):
stack = [-1]; res = 0
for i,ch in enumerate(s):
if
ch=='(':
stack.append(i)
else:
stack.pop()
if not
stack:
stack.append(i)
else: res = max(res, i - stack[-1])
return res
print(longest_valid_parentheses(')()())')) # 4

40. Count occurrences of elements (Counter)


from collections import Counter
def counts(arr): return Counter(arr)
print(counts([1,2,2,3])) #
Counter({2:2,1:1,3:1})

41. Longest substring without repeating characters (sliding window)


def length_of_longest_substring(s):
seen = {}
start = 0; maxlen = 0
for i,ch in
enumerate(s):
if ch in seen and seen[ch] >= start:
start = seen[ch] + 1
seen[ch] = i
maxlen = max(maxlen, i - start + 1)
return maxlen
print(length_of_longest_substring('abcabcbb')) # 3

42. Minimum window substring (brief solution sketch)


# Full optimal solution is lengthy; here's a common approach:
# Use two pointers + counts dict to
expand/contract window to cover required chars.
def min_window(s, t):
from collections import
Counter
need = Counter(t); missing = len(t)
i = start = end = 0
for j,ch in enumerate(s,
1):
if need[ch] > 0: missing -= 1
need[ch] -= 1
if missing == 0:
while i < j and need[s[i]] < 0:
need[s[i]] += 1; i += 1
if not end or j
- i < end - start: start, end = i, j
need[s[i]] += 1; missing += 1; i += 1
return
s[start:end]

43. Word break (DP) - check if can be segmented


def word_break(s, wordDict):
n = len(s)
dp = [False]*(n+1); dp[0]=True
for i in range(1,
n+1):
for w in wordDict:
if dp[i-len(w)] and s[i-len(w):i]==w:
dp[i]=True; break
return dp[n]

print(word_break('leetcode', ['leet','code'])) # True

44. Coin change - number of ways (DP)


def coin_change_ways(coins, amount):
dp = [0]*(amount+1); dp[0]=1
for coin in coins:
for x in range(coin, amount+1):
dp[x] += dp[x-coin]
return dp[amount]
print(coin_change_ways([1,2,5], 5)) # 4

45. Knapsack 0/1 (DP) - maximize value (brief)


def knapsack(values, weights, W):
n = len(values)
dp = [0]*(W+1)
for i in range(n):
for w in range(W, weights[i]-1, -1):
dp[w] = max(dp[w], dp[w-weights[i]] + values[i])
return dp[W]

46. Matrix spiral order


def spiral_order(matrix):
if not matrix: return []
res = []
top, bottom, left, right =
0, len(matrix)-1, 0, len(matrix[0])-1
while top <= bottom and left <= right:
for j in
range(left, right+1): res.append(matrix[top][j])
top += 1
for i in range(top,
bottom+1): res.append(matrix[i][right])
right -= 1
if top <= bottom:
for
j in range(right, left-1, -1): res.append(matrix[bottom][j])
bottom -= 1
if left
<= right:
for i in range(bottom, top-1, -1): res.append(matrix[i][left])
left += 1
return res

47. Rotate matrix by 90 degrees (in-place)


def rotate_matrix(a):
n = len(a)
for i in range(n):
for j in range(i, n): a[i]
[j], a[j][i] = a[j][i], a[i][j]
for row in a:
row.reverse()
return a

48. Search in 2D matrix (sorted rows+cols) - staircase search


def search_matrix(mat, target):
if not mat: return False
r, c = 0, len(mat[0]) - 1
while
r < len(mat) and c >= 0:
if mat[r][c] == target: return True
if mat[r][c] > target:
c -= 1
else: r += 1
return False

49. Find longest increasing subsequence length (n log n)


def lis_length(nums):
import bisect
sub = []
for x in nums:
i =
bisect.bisect_left(sub, x)
if i == len(sub): sub.append(x)
else: sub[i] = x
return len(sub)

print(lis_length([10,9,2,5,3,7,101,18])) # 4

50. Serialize / deserialize binary tree (preorder) - simple approach


def serialize(root):
vals = []
def dfs(n):
if not n: vals.append('#'); return
vals.append(str(n.val)); dfs(n.left); dfs(n.right)
dfs(root); return ' '.join(vals)

def
deserialize(data):
vals = iter(data.split())
def dfs():
val = next(vals)
if
val == '#': return None
node = TreeNode(int(val))
node.left = dfs(); node.right =
dfs()
return node
return dfs()

You might also like