Placement Impcodes
Placement Impcodes
n=int(input())
t=n
s=0
while n>0:
r=n%10
s=s*10+r
n=n//10
print(s)
Fibonacci sequence is a sequence in which each number is the sum of the two
preceding ones. 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ....
n=int(input())
n1, n2 = 0, 1
for i in range(2,n):
n3=n1+n2
n1=n2
n2=n3
print(n3,end=" ")
GCD.
The greatest common divisor (GCD) of two or more numbers is the greatest common
factor number that divides them, exactly. It is also called the highest common factor.
a=int(input())
b=int(input())
def gcd(a, b):
if(b == 0):
return abs(a)
else:
return gcd(b, a % b)
print(gcd(a,b))
LCM.
import math
a,b=map(int,input().split())
print(abs(a*b)//math.gcd(a,b))
Perfect Number.
A positive integer that is equal to the sum of its proper divisors. The smallest perfect
number is 6, which is the sum of 1, 2, and 3.
n=int(input())
s=0
for i in range(1,n):
if(n%i==0):
s=s+i
if(s==n):
print("Perfect")
else:
print("Not Perfect")
Two strings are anagrams if they contain the same characters but in a different
order. Note that a letter has to be used only once.
s1=input()
s2=input()
if len(s1)!=len(s2):
print('not anagram')
else:
s1=sorted(s1)
s2=sorted(s2)
if s1==s2:
print('Anagram')
else:
print('Not Anagram')
s1=input()
s2=s1[::-1]
if s1==s2:
print('Palindromic')
else:
print('Non Palindromic')
Calculate frequency of characters in a string.
s=input()
c=input()
f=0
f=s.count(c)
print(str(f))
year = int(input())
if (year%400 == 0) or (year%4==0 and year%100!=0):
print("Leap Year")
else:
print("Not a Leap Year")
s=input()
for i in s:
c=0
for j in s:
if i==j:
c=c+1
if c>1:
break
if c==1:
print(i,end=" ")
s=input()
s1=input()
s2=input()
s=s.replace(s1,s2)
print(s)
Sum of natural numbers using recursion.
def nnrc(n):
if n == 0:
return n
return n + nnrc(n-1)
n = int(input())
print(nnrc(n))
s1=input()
s2=''
for i in s1:
if(ord(i)>=65 and ord(i)<=90) or (ord(i)>=97 and ord(i)<=122):
s2=s2+i
print(s2)
s=input()
s="".join(s.split()) #s=’.’.join(s.split(‘.’)[::-1])
print(s)
def rev_wrds(s):
words=s.split()
rev_wrd=[word[::-1] for word in words]
rev_str=' '.join(rev_wrd)
return rev_str
s=input()
print(rev_wrds(s))
Factorial of a number.
n=int(input())
f=1
for i in range(2,n+1):
f*=i
print(f)
Binary to decimal convertion.
n=int(input())
binum,dcnum=n,0
base=1
while n>0:
r=n%10
dcnum=dcnum+r*base
n=n//10
base=base*2
print(dcnum)
Automorphic number.
A number is called an Automorphic number if and only if its square ends in the same
digits as the number itself. Ex: 25*25=625 & 76*76=5776.
n=int(input())
l=len(str(n))
sq=n**2
last=sq%pow(10,l)
if last==n:
print('Automorphic')
else:
print('Not Automorphic')
Palindrome number.
n=int(input("Enter number:"))
temp=n
rev=0
while(n>0):
dig=n%10
rev=rev*10+dig
n=n//10
if(temp==rev):
print("The number is a palindrome!")
else:
print("The number isn't a palindrome!")
arr = list(map(int,input().split()))
mn=arr[0]
for i in range(len(arr)):
if arr[i]<mn:
mn=arr[i]
print(mn)
n=int(input())
s=0
while(n!=0):
r=n%10
s+=r
n=n//10
print(s)
Sum of fractions.
import fractions
f1=fractions.Fraction(2,3)
f2=fractions.Fraction(3,7)
print(f1+f2)
a,b,c=map(int,input().split())
import math
def findRoots(a, b, c):
if a == 0:
print("Invalid")
return -1
d=b*b-4*a*c
sq = math.sqrt(abs(d))
if d > 0:
print("Roots are real and different ")
print((-b + sq)/(2 * a))
print((-b - sq)/(2 * a))
elif d == 0:
print("Roots are real and same")
print(-b / (2*a))
else:
print("Roots are complex")
print(- b / (2*a), " + i", sq)
print(- b / (2*a), " - i", sq)
findRoots(a, b, c)
def 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
arr = list(map(int,input().split()))
print("Before sorting: ", arr)
arr = sort(arr)
print("After sorting: ", arr)
Search element in a list.
n=int(input())
print(bin(n).count('1')) # print(bin(2)[2:])
Generate all the prime numbers between one & the given number.
a whole number greater than 1 whose only factors are 1 and itself.
2, 3, 5, 7, 11, 13, 17, 19, 23 and 29.
def checkPrime(n):
if n < 2:
return 0
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return 0
return 1
r1=int(input())
r2=int(input())
for i in range(r1,r2+1):
if checkPrime(i):
print(i,end=" ")
Heap Sort.
import heapq
def heap_sort(arr):
heapq.heapify(arr)
result = []
while arr:
result.append(heapq.heappop(arr))
return result
arr = list(map(int,input().split()))
print("Input Array: ", arr)
print("Sorted Array: ", heap_sort(arr))
n=int(input())
s=0
while n>0:
s+=n%10
n=n//10
print(s)
s = input()
words = s.split(' ')
string = []
for word in words:
string.insert(0, word)
print(" ".join(string))
n=int(input())
l=list(map(int,input().split()))[:n]
print(' '.join(map(str,l)))
“for printing 1 2 3 instead of [1,2,3] and also avoids EOF error”
Sort alphabets and digits in a string.
s = input()
alphabets=[]
digits=[]
for ch in s:
if ch.isalpha():
alphabets.append(ch)
else:
digits.append(ch)
result="".join(sorted(alphabets)+sorted(digits))
print(result)
def check(string):
p=set(string)
s = {'0','1'}
if s==p or p== {'0'} or p== {'1'}:
print('Yes')
else:
print('No')
string=input()
check(string)
a=input()
b=input()
s=bin(int(a,2)+int(b,2))[2:]
print(s)
def find_missing_number(arr):
n = len(arr)
total_sum = n * (n + 1) // 2
arr_sum = sum(arr)
missing_number = total_sum - arr_sum
return missing_number
arr = list(map(int,input().split()))
missing_number = find_missing_number(arr)
print(f"The missing number is: {missing_number}")
Valid Parentheses or not.
def isValidParentheses(s):
stack = []
pairs = {'(': ')', '[': ']', '{': '}'}
for char in s:
if char in pairs: # If it's an opening bracket
stack.append(char)
elif stack and pairs[stack[-1]] == char: # If it's a matching closing bracket
stack.pop()
else: # Either unmatched closing bracket or empty stack
return False
return not stack # Return True if stack is empty (all matched)
s = input("Enter a string with brackets: ")
print(isValidParentheses(s))
l=list(map(int,input().split()))
r=sorted(list(set(l))) # l=" ".join(map(str, l))
print(r)
n=int(input())
for _ in range(n):
l=list(map(int,input().split()))
for i in range(len(l)):
for j in range(i+1,len(l)):
if l[i]>l[j]:
l[i],l[j]=l[j],l[i]
print(l)
Finding middle element from the list.
def midele(l):
length = len(l)
midx = length // 2
if length % 2 == 0:
mid = math.ceil((l[midx - 1] + l[midx]) / 2)
else:
mid = l[midx]
return mid
import math
l = list(map(int,input().split()))
r = midele(l)
print(r)
def int_to_roman(num):
roman_nums = [(1000, 'M'), (900, 'CM'), (500, 'D'), (400, 'CD'),(100, 'C'), (90,
'XC'), (50, 'L'), (40, 'XL'),(10, 'X'), (9, 'IX'), (5, 'V'), (4, 'IV'), (1, 'I')]
result = ''
for val, nm in roman_nums:
while num>=val:
result+=nm
num-=val
return result
num=int(input())
print(int_to_roman(num))
string = input()
vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']
result = ""
for i in range(len(string)):
if string[i] not in vowels:
result = result + string[i]
print(result)
Harshad number.
A number is said to be the Harshad number if it is divisible by the sum of its digit.
For example, if number is 156, then sum of its digit will be 1 + 5 + 6 = 12. Since
156 is divisible by 12. So, 156 is a Harshad number.
def harshad(num):
digits = [int(digit) for digit in str(num)]
s=sum(digits)
return num%s==0
t=int(input())
for i in range(t):
num=int(input())
if harshad(num):
print("Harshad")
else:
print("not Harshad")
def check_isogram(str1):
return len(str1) == len(set(str1.lower()))
print(check_isogram("Python"))
n=int(input())
a=list(map(int,input().split()))[:n]
print(sum(a))
Two Sum - Given an array of integers, find two numbers such that they add up
to a specific target number.
def Fibonacci(n):
if n == 0 or n==1:
return 0
elif n == 2:
return 1
else:
return Fibonacci(n-1)+Fibonacci(n-2)
n=int(input())
print(Fibonacci(n))
def contains_digits(s):
for char in s:
if char.isdigit():
return True
return False
s = input()
if contains_digits(s):
print("The string contains digits.")
else:
print("The string does not contain digits.")
Print the following pattern:
*****
*****
*****
*****
*****
for i in range(1,6):
for j in range(1,6):
print('*',end=" ")
print()
*
**
***
****
*****
for i in range(1,6):
for j in range(i):
print('*',end=" ")
print()
A
AB
ABC
ABCD
ABCDE
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(1,6):
for j in range(i):
print(s[j],end=" ")
print()
Print the following pattern:
E
ED
EDC
EDCB
EDCBA
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(1,6):
for j in range(i):
print(chr(65+5-1-j),end=" ")
print()
ABCDE
ABCD
ABC
AB
A
s="ABCDEFGHIJKLMNOPQRSTUVWXYZ"
for i in range(1,6):
for j in range(6-i):
print(chr(65+j),end=" ")
print()
def longestPalindrome(s):
max_len = 0
max_word = ""
for first in range(len(s)):
for second in range(first+1, len(s)+1):
word = s[first:second]
if (word == word[::-1]):
if max_len < len(word):
max_len = len(word)
max_word = word
return max_word
s=input()
print(longestPalindrome(s))
Longest common prefix.
def longestCommonPrefix(strings):
if not strings:
return ""
strings.sort()
first = strings[0]
last = strings[-1]
prefix = ""
for i in range(len(first)):
if i < len(last) and first[i] == last[i]:
prefix += first[i]
else:
break
return prefix
strings = ["flower", "flow", "flight"]
print(longestCommonPrefix(strings))
s = sorted(input())
low = up = odd = even = ''
for char in s:
if char.islower():
low += char
elif char.isupper():
up += char
elif int(char)%2 == 1:
odd += char
else:
even += char
print(low + up + odd + even)
Rotate List by N positions.
a=int(input())
arr=list(map(int,input().split()))[:a]
n=int(input())
for i in range(n):
temp=arr[0]
arr[0]=arr[a-1]
for j in range(1,a):
s=arr[j]
arr[j]=temp
temp=s
for i in arr:
print(i,end=" ")
def WordsFound(sentences):
max_words = 0
for sentence in sentences:
words = sentence.split()
num_words = len(words)
if num_words > max_words:
max_words = num_words
return max_words
sentences=["Dattu has very big boobs", "Nitin is fucking handsome baby boo"]
print(WordsFound(sentences))
Ugly Number or not.
An ugly number is a positive integer whose prime factors are limited to 2, 3, and 5.
def isUgly(num):
if num <= 0:
return 'Not an Ugly Number'
for i in [2, 3, 5]:
while num % i == 0:
num /= i
return "Ugly Number" if num == 1 else "Not an Ugly Number"
num=int(input())
print(isUgly(num))
a=[1,3,4,2,2,1,4,7,7]
d={}
for i in a:
if i in d:
d[i]+=1
else:
d[i]=1
print(d)
class Stack:
def __init__(self):
self.items = []
def push(self, item):
self.items.append(item)
def pop(self):
if not self.is_empty():
return self.items.pop()
else:
return "Stack is empty"
def peek(self):
if not self.is_empty():
return self.items[-1]
else:
return "Stack is empty"
def is_empty(self):
return len(self.items) == 0
def size(self):
return len(self.items)
def display(self):
print(self.items)
stack = Stack()
stack.push(1)
stack.push(2)
stack.push(3)
stack.display() # Output: [1, 2, 3]
print(stack.pop()) # Output: 3
stack.display() # Output: [1, 2]
print(stack.peek()) # Output: 2
print(stack.is_empty()) # Output: False
print(stack.size()) # Output: 2
Queue program.
class Node:
def __init__(self, data=None):
self.data = data
self.next = None
class Queue:
def __init__(self):
self.front = None
self.rear = None
def is_empty(self):
return self.front is None
def enqueue(self, data):
new_node = Node(data)
if self.rear is None:
self.front = self.rear = new_node
return
self.rear.next = new_node
self.rear = new_node
def dequeue(self):
if self.is_empty():
print("Queue is empty")
return None
temp = self.front
self.front = temp.next
if self.front is None:
self.rear = None
return temp.data
def display(self):
if self.is_empty():
print("Queue is empty")
return
current_node = self.front
nodes = []
while current_node:
nodes.append(current_node.data)
current_node = current_node.next
print(" <- ".join(map(str, nodes)))
queue = Queue()
queue.enqueue(1)
queue.enqueue(2)
queue.display() # Output: 1 <- 2
print(queue.dequeue()) # Output: 1
Nearest Prime Number.
def is_prime(num):
if num <= 1:
return False
for i in range(2, int(num**0.5) + 1):
if num % i == 0:
return False
return True
def nearest_prime(n):
if is_prime(n):
return n
lower = n - 1
while lower > 1:
if is_prime(lower):
return lower
lower -= 1
def print_unique_nearest_primes_up_to(n):
seen_primes = set()
for i in range(2, n):
nearest = nearest_prime(i)
if nearest not in seen_primes:
print(nearest)
seen_primes.add(nearest)
n = int(input())
print_unique_nearest_primes_up_to(n)
class Node:
def __init__(self, data):
self.data = data
self.next = None
class LinkedList:
def __init__(self):
self.head = None
def push(self, data):
new_node = Node(data)
new_node.next = self.head
self.head = new_node
def reverse(self):
prev = None
current = self.head
while current:
next_node = current.next
current.next = prev
prev = current
current = next_node
self.head = prev
def print_list(self):
temp = self.head
while temp:
print(temp.data, end=" ")
temp = temp.next
print()
llist = LinkedList()
llist.push(1)
llist.push(2)
llist.push(3)
llist.push(4)
print("Original Linked List:")
llist.print_list()
llist.reverse()
print("Reversed Linked List:")
llist.print_list()
Binary tree is BST or not.
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
def is_bst_util(node, left, right):
# Base case: An empty tree is a BST
if node is None:
return True
# If this node violates the min/max constraint, it's not a BST
if node.data <= left or node.data >= right:
return False
# Recursively check the left and right subtrees
return (is_bst_util(node.left, left, node.data) and
is_bst_util(node.right, node.data, right))
def is_bst(root):
# Initialize with the minimum and maximum possible values
return is_bst_util(root, float('-inf'), float('inf'))
root = Node(10)
root.left = Node(5)
root.right = Node(20)
root.left.left = Node(1)
root.left.right = Node(8)
root.right.left = Node(15)
root.right.right = Node(30)
if is_bst(root):
print("The tree is a binary search tree.")
else:
print("The tree is not a binary search tree.")
Merge 2 sorted arrays.
Easy Questions
1. What is Python?
Python is a high-level, interpreted programming language known for its simplicity
and readability. It supports multiple programming paradigms, including
procedural, object-oriented, and functional programming.
5. What is the difference between append() and extend() methods for lists?
append() adds a single element to the end of a list, while extend() adds multiple
elements by appending elements from an iterable like another list.
6. Explain the difference between remove() and pop() methods for lists.
remove() deletes the first occurrence of a specified value, whereas pop() removes
and returns the element at a specified index.
Medium Questions
10. What is the difference between shallow copy and deep copy?
A shallow copy creates a new object but inserts references into it. A deep copy
creates a new object and recursively copies all objects found in the original.
10. What are the advantages of a linked list over an array? In which scenarios do
we use Linked List and when Array?
This is another frequently asked data structure interview questions! Advantages of
a linked list over an array are:
i. Insertion and Deletion
Insertion and deletion of nodes is an easier process, as we only update the address
present in the next pointer of a node. It’s expensive to do the same in an array as
the room has to be created for the new elements and existing elements must be
shifted.
ii. Dynamic Data Structure
As a linked list is a dynamic data structure, there is no need to give an initial size
as it can grow and shrink at runtime by allocating and deallocating memory.
However, the size is limited in an array as the number of elements is statically
stored in the main memory.
iii. No Wastage of Memory
As the size of a linked list can increase or decrease depending on the demands of
the program, and memory is allocated only when required, there is no memory
wasted. In the case of an array, there is memory wastage. For instance, if we
declare an array of size 10 and store only five elements in it, then the space for
five elements is wasted.
iv. Implementation
Data structures like stack and queues are more easily implemented using a linked
list than an array.
Some scenarios where we use linked list over array are:
When we know the upper limit on the number of elements in advance
When there are a large number of add or remove operations
When there are no large number of random access to elements
When we want to insert items in the middle of the list, such as when implementing
a priority queue
Some scenarios in which we use array over the linked list are:
When we need to index or randomly access elements
When we know the number of elements in the array beforehand, so we can
allocate the correct amount of memory
When we need speed when iterating through all the elements in the sequence
When memory is a concern; filled arrays use less memory than linked lists, as each
element in the array is the data but each linked list node requires the data as well
as one or more pointers to the other elements in the linked list
In summary, we consider the requirements of space, time, and ease of
implementation to decide whether to use a linked list or array.
11. What is a doubly-linked list? Give some examples.
It is a complex type (double-ended LL) of a linked list in which a node has two
links, one that connects to the next node in the sequence and another that connects
to the previous node. This allows traversal across the data elements in both
directions.
Examples include:
A music playlist with next and previous navigation buttons
The browser cache with BACK-FORWARD visited pages
The undo and redo functionality on a browser, where you can reverse the node to
get to the previous page
38. What are the advantages of binary search over a linear search?
In a sorted list:
A binary search is more efficient than a linear search because we perform fewer
comparisons. With linear search, we can only eliminate one element per
comparison each time we fail to find the value we are looking for, but with the
binary search, we eliminate half the set with each comparison.
Binary search runs in O(log n) time compared to linear search’s O(n) time. This
means that the more of the elements present in the search array, the faster is binary
search compared to a linear search.
42. Name the ways to determine whether a linked list has a loop.
Using hashing
Using the visited nodes method (with or without modifying the basic linked list
data structure)
Floyd’s cycle-finding algorithm