code 820275 1280
Spread the love

Table of Contents

Placement-Preparation

Preparing for placements often involves mastering coding questions, as they are a critical component of technical interviews. Start by understanding fundamental concepts like data structures (arrays, linked lists, trees) and algorithms (sorting, searching, dynamic programming). Practice is key—solve a variety of problems on platforms like LeetCode, HackerRank, or Codeforces to improve your problem-solving skills. Focus on writing clean, efficient code and understanding the time and space complexities. Reviewing previous interview questions from companies can provide valuable insights. Consistency in practice and learning from mistakes will significantly boost your confidence and performance in coding interviews.

Coding Questions

1. Reverse a String

C++:

#include <iostream>

#include <algorithm>

using namespace std;
int main() {
string str;
cout << "Enter a string: ";
cin >> str;
reverse(str.begin(), str.end());
cout << "Reversed string: " << str << endl;
return 0;
}

Python:

str = input("Enter a string: ")
reversed_str = str[::-1]
print("Reversed string:", reversed_str)

2. Check if a Number is Prime

C++:

#include <iostream>

using namespace std;
bool isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i < n; i++) {
if (n % i == 0) return false;
}
return true;
}
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
if (isPrime(n))
cout << n << " is a prime number." << endl;
else

cout << n << " is not a prime number." << endl;
return 0;
}

Python:

def is_prime(n):
if n <= 1:
return False

for i in range(2, n):
if n % i == 0:
return False

return True
n = int(input("Enter a number: "))
if is_prime(n):
print(n, "is a prime number.")
else:
print(n, "is not a prime number.")

3. Find the Factorial of a Number

C++:

#include <iostream>

using namespace std;
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
int main() {
int n;
cout << "Enter a number: ";
cin >> n;
cout << "Factorial of " << n << " is " << factorial(n) << endl;
return 0;
}

Python:

def factorial(n):
if n <= 1:
return 1

return n * factorial(n - 1)
n = int(input("Enter a number: "))
print("Factorial of", n, "is", factorial(n))

4. Find the Fibonacci Series Up to n Terms

C++:

#include <iostream>

using namespace std;
void printFibonacci(int n) {
int a = 0, b = 1, c;
for (int i = 1; i <= n; i++) {
cout << a << " ";
c = a + b;
a = b;
b = c;
}
cout << endl;
}
int main() {
int n;
cout << "Enter the number of terms: ";
cin >> n;
printFibonacci(n);
return 0;
}

Python:

def fibonacci(n):
a, b = 0, 1

for _ in range(n):
print(a, end=" ")
a, b = b, a + b
print()
n = int(input("Enter the number of terms: "))
fibonacci(n)

5. Check if a String is a Palindrome

C++:

#include <iostream>

using namespace std;
bool isPalindrome(string str) {
int n = str.length();
for (int i = 0; i < n / 2; i++) {
if (str[i] != str[n - i - 1]) return false;
}
return true;
}
int main() {
string str;
cout << "Enter a string: ";
cin >> str;
if (isPalindrome(str))
cout << str << " is a palindrome." << endl;
else

cout << str << " is not a palindrome." << endl;
return 0;
}

Python:

def is_palindrome(s):
return s == s[::-1]
s = input("Enter a string: ")
if is_palindrome(s):
print(s, "is a palindrome.")
else:
print(s, "is not a palindrome.")

6. Find the GCD of Two Numbers

C++:

#include <iostream>
using namespace std;
int gcd(int a, int b) {
if (b == 0)
return a;
return gcd(b, a % b);
}
int main() {
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;
cout << "GCD of " << a << " and " << b << " is " << gcd(a, b) << endl;
return 0;
}

Python:

def gcd(a, b):
while b:
a, b = b, a % b
return a
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("GCD of", a, "and", b, "is", gcd(a, b))

7. Find the LCM of Two Numbers

C++:

#include <iostream>

using namespace std;
int gcd(int a, int b) {
return b == 0 ? a : gcd(b, a % b);
}
int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
int main() {
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;
cout << "LCM of " << a << " and " << b << " is " << lcm(a, b) << endl;
return 0;
}

Python:

def gcd(a, b):
while b:
a, b = b, a % b
return a
def lcm(a, b):
return (a * b) // gcd(a, b)
a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
print("LCM of", a, "and", b, "is", lcm(a, b))

8. Sort an Array Using Bubble Sort

C++:

#include <iostream>

using namespace std;
void bubbleSort(int arr[], int n) {
for (int i = 0; i < n-1; i++) {
for (int j = 0; j < n-i-1; j++) {
if (arr[j] > arr[j+1]) {
swap(arr[j], arr[j+1]);
      }
     }
   }
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];
cout << "Enter the elements: ";
for (int i = 0; i < n; i++) cin >> arr[i];
bubbleSort(arr, n);
cout << "Sorted array: ";
for (int i = 0; i < n; i++) cout << arr[i] << " ";
cout << endl;
return 0;
}

Python:

def bubble_sort(arr):
n = len(arr)
for i in range(n-1):
for j in range(n-i-1):
if arr[j] > arr[j+1]:
arr[j], arr[j+1] = arr[j+1], arr[j]
arr = list(map(int, input("Enter the elements of the array: ").split()))
bubble_sort(arr)
print("Sorted array:", arr)

9. Sort an Array Using Quick Sort

C++:

#include <iostream>

using namespace std;
int partition(int arr[],
int low, int high) {
int pivot = arr[high];
int i = low - 1;
for (int j = low; j < high; j++) {
if (arr[j] < pivot) {
i++;
swap(arr[i], arr[j]);
}
}
swap(arr[i+1], arr[high]);
return i + 1;
}
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];
cout << "Enter the elements: ";
for (int i = 0; i < n; i++) cin >> arr[i];
quickSort(arr, 0, n - 1);
cout << "Sorted array: ";
for (int i = 0; i < n; i++) cout << arr[i] << " ";
cout << endl;
return 0;
}

Python:

def partition(arr, low, high):
pivot = arr[high]
i = low - 1

for j in range(low, high):
if arr[j] < pivot:
i += 1
arr[i], arr[j] = arr[j], arr[i]
arr[i+1], arr[high] = arr[high], arr[i+1]
return i + 1

def quick_sort(arr, low, high):

if low < high:
pi = partition(arr, low, high)
quick_sort(arr, low, pi - 1)
quick_sort(arr, pi + 1, high)
arr = list(map(int, input("Enter the elements of the array: ").split()))
quick_sort(arr, 0, len(arr) - 1)
print("Sorted array:", arr)

10. Implement Binary Search

C++:

#include <iostream>

using namespace std;
int binarySearch(int arr[], int n, int x) {
int left = 0, right = n - 1;
while (left <= right) {
int mid = left + (right - left) / 2;
if (arr[mid] == x) return mid;
if (arr[mid] < x) left = mid + 1;
else right = mid - 1;
}
return -1;
}
int main() {
int n, x;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];
cout << "Enter the elements: ";
for (int i = 0; i < n; i++) cin >> arr[i];

cout << "Enter the element to search: ";
cin >> x;
int result = binarySearch(arr, n, x);
if (result != -1)
cout << "Element found at index " << result << endl;
else

cout << "Element not found" << endl;
return 0;
}

Python:

def binary_search(arr, x):
left, right = 0, len(arr) - 1

while left <= right:
mid = left + (right - left) // 2

if arr[mid] == x:
return mid
elif arr[mid] < x:
left = mid + 1

else:
right = mid - 1

return -1

arr = list(map(int, input(“Enter the elements of the array: “).split()))

x = int(input("Enter the element to search: "))
result = binary_search(arr, x)
if result != -1:
print("Element found at index", result)
else:
print("Element not found")

11. Find the Maximum and Minimum Elements in an Array

C++:

#include <iostream>

using namespace std;
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];
cout << "Enter the elements: ";
for (int i = 0; i < n; i++) cin >> arr[i];
int maxElement = arr[0], minElement = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > maxElement) maxElement = arr[i];
if (arr[i] < minElement) minElement = arr[i];
}
cout << "Maximum element: " << maxElement << endl;
cout << "Minimum element: " << minElement << endl;
return 0;
}

Python:

arr = list(map(int, input("Enter the elements of the array: ").split()))
max_element = max(arr)
min_element = min(arr)
print("Maximum element:", max_element)
print("Minimum element:", min_element)

12. Find the Second Largest Element in an Array

C++:

#include <iostream>  
using namespace std;
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];
cout << "Enter the elements: ";
for (int i = 0; i < n; i++) cin >> arr[i];
int first = INT_MIN, second = INT_MIN;
for (int i = 0; i < n; i++) {
if (arr[i] > first) {
second = first;
first = arr[i];
}
else if (arr[i] > second && arr[i] != first) {
second = arr[i];
}
}
if (second == INT_MIN)
cout << "No second largest element found." << endl;
else
cout << "Second largest element: " << second << endl;
return 0;
}

Python:

arr = list(map(int, input("Enter the elements of the array: ").split()))
first = second = float('-inf')
for num in arr:
if num > first:
second = first
first = num
elif num > second and num != first:
second = num
if second == float('-inf'):
print("No second largest element found.")
else:
print("Second largest element:", second)

13. Find the Sum of Digits of a Number

C++:

#include <iostream>

using namespace std;
int main() {
int n, sum = 0;
cout << "Enter a number: ";
cin >> n;
while (n != 0) {
sum += n % 10;
n /= 10;
}
cout << "Sum of digits: " << sum << endl;
return 0;
}

Python:

n = int(input("Enter a number: "))
sum_digits = 0
while n != 0:
sum_digits += n % 10

n //= 10

print(“Sum of digits:”, sum_digits)


14. Swap Two Numbers Without Using a Temporary Variable

C++:

#include <iostream>

using namespace std;
int main() {
int a, b;
cout << "Enter two numbers: ";
cin >> a >> b;
a = a + b;
b = a - b;
a = a - b;
cout << "After swapping: a = " << a << ", b = " << b << endl;
return 0;
}

Python:

a = int(input("Enter first number: "))
b = int(input("Enter second number: "))
a, b = b, a
print("After swapping: a =", a, ", b =", b)

15. Print All Prime Numbers Up to n

C++:

#include <iostream>

using namespace std;
bool isPrime(int n) {
if (n <= 1) return false;
for (int i = 2; i < n; i++) {
if (n % i == 0) return false;
}
return true;
}
int main() {
int n;
cout << "Enter the upper limit: ";
cin >> n;
cout << "Prime numbers up to " << n << ": ";
for (int i = 2; i <= n; i++) {
if (isPrime(i)) cout << i << " ";
}
cout << endl;
return 0;
}

Python:

def is_prime(n):
if n <= 1:
return False

for i in range(2, n):
if n % i == 0:
return False

return True

n = int(input(“Enter the upper limit: “))

print("Prime numbers up to", n, ":")
for i in range(2, n + 1):
if is_prime(i):
print(i, end=" ")
print()

16. Check if Two Strings Are Anagrams

C++:

#include <iostream>

#include <algorithm>

using namespace std;
bool areAnagrams(string str1, string str2) {
if (str1.length() != str2.length()) return false;
sort(str1.begin(), str1.end());
sort(str2.begin(), str2.end());
return str1 == str2;
}
int main() {
string str1, str2;
cout << "Enter first string: ";
cin >> str1;
cout << "Enter second string: ";
cin >> str2;
if (areAnagrams(str1, str2))
cout << "The strings are anagrams." << endl;
else
cout << "The strings are not anagrams." << endl;
     return 0;
}

Python:

def are_anagrams(str1, str2):
return
sorted(str1) == sorted(str2)
str1 = input("Enter first string: ")
str2 = input("Enter second string: ")
if are_anagrams(str1, str2):
print("The strings are anagrams.")
else:
print("The strings are not anagrams.")

17. Remove Duplicates from an Array

C++:

#include <iostream>

#include <set>
#include <vector>
using namespace std;
vector<int> removeDuplicates(int arr[], int n) {
set<int> s(arr, arr + n);
return vector<int>(s.begin(), s.end());
}
int main() {
int n;
cout << "Enter the number of elements: ";
cin >> n;
int arr[n];
cout << "Enter the elements: ";
for (int i = 0; i < n; i++) cin >> arr[i];
vector<int> result = removeDuplicates(arr, n);
cout << "Array after removing duplicates: ";
for (int i : result) cout << i << " ";
cout << endl;
return 0;
}

Python:

arr = list(map(int, input("Enter the elements of the array: ").split()))
arr = list(set(arr))
print("Array after removing duplicates:", arr)

21. Implement a Stack using an Array

C++ Implementation:

#include <iostream>
#define MAX 1000
class Stack {
int top;
public:
int a[MAX]; // Maximum size of Stack
Stack() { top = -1; }
bool push(int x);
int pop();
bool isEmpty();
};
bool Stack::push(int x){
if (top >= (MAX - 1)) {
std::cout << "Stack Overflow";
return false;
} else {
a[++top] = x;
std::cout << x << " pushed into stack\n";
return true;
}
}
int Stack::pop(){
if (top < 0) {
std::cout << "Stack Underflow";
return 0;
}
else
{
int x = a[top--];
return x;
}
}
bool Stack::isEmpty(){
return (top < 0);
}
int main(){
Stack stack;
stack.push(10);
stack.push(20);
stack.push(30);
std::cout << stack.pop() << " popped from stack\n";
return 0;
}

Python Implementation:

class Stack:
def __init__(self):
self.stack = []
def push(self, item):
self.stack.append(item)
print(f"{item} pushed into stack")
def pop(self):
if not self.is_empty():
return self.stack.pop()
else:
print("Stack Underflow")
return None
def is_empty(self):
return len(self.stack) == 0
# Example usage:

stack = Stack()
stack.push(10)
stack.push(20)
stack.push(30)
print(f"{stack.pop()} popped from stack")

22. Implement a Queue using an Array

C++ Implementation:

#include <iostream>
#define MAX 1000
class Queue {
int front,rear;
public:
int a[MAX];
Queue() { front = rear = -1; }
bool enqueue(int x);
int dequeue();
bool isEmpty();
};
bool Queue::enqueue(int x){
if (rear >= (MAX - 1)) {
std::cout << "Queue Overflow";
return false;
} else {
if (front == -1) front = 0;
a[++rear] = x;
std::cout << x << " enqueued into queue\n";
return true;
}
}
int Queue::dequeue(){
if (front > rear || front == -1) {
std::cout << "Queue Underflow";
return 0;
} else {
int x = a[front++];
return x;
}
}
bool Queue::isEmpty(){
return (front > rear || front == -1);
}
int main(){
Queue queue;
queue.enqueue(10);
queue.enqueue(20);
queue.enqueue(30);
std::cout << queue.dequeue() << " dequeued from queue\n";
return 0;
}

Python Implementation:

class Queue:
def __init__(self):
self.queue = []
def enqueue(self, item):
self.queue.append(item)
print(f"{item} enqueued into queue")
def dequeue(self):
if not self.is_empty():
return self.queue.pop(0)
else:
print("Queue Underflow")
return None
def is_empty(self):
return len(self.queue) == 0
# Example usage:

queue = Queue()
queue.enqueue(10)
queue.enqueue(20)
queue.enqueue(30)
print(f"{queue.dequeue()} dequeued from queue")

23. Find the Length of a String Without Using Built-in Functions

C++ Implementation:

#include <iostream>
int stringLength(char* str){
int length = 0;
while (str[length] != '\0') {
length++;
}
return length;
}
int main(){
char str[] = "Hello, World!";
std::cout << "Length of the string: " << stringLength(str);
return 0;
}

Python Implementation:

def string_length(s):
length = 0
for _ in s:
length += 1
return length
# Example usage:

s = "Hello, World!"
print(f"Length of the string: {string_length(s)}")

24. Count the Occurrences of Each Character in a String

C++ Implementation:

#include <iostream>
#include <unordered_map>
void countOccurrences(char* str){
std::unordered_map<char, int> countMap;
for (int i = 0; str[i] != '\0'; i++) {
countMap[str[i]]++;
}
for (auto pair : countMap) {
std::cout << pair.first << " occurs " << pair.second << " times\n";
}
}
int main(){
char str[] = "Hello, World!";
countOccurrences(str);
return 0;
}

Python Implementation:

def count_occurrences(s):
count_map = {}
for char in s:
if char in count_map:
count_map[char] += 1
else:
count_map[char] = 1
for char, count in count_map.items():
print(f"{char} occurs {count} times")
# Example usage:

s = "Hello, World!"
count_occurrences(s)

25. Merge Two Sorted Arrays

C++ Implementation:

#include <iostream>
#include <vector>
std::vector<int> mergeSortedArrays(std::vector<int>& arr1, std::vector<int>& arr2){
std::vector<int> result;
int i = 0,
j = 0;
while (i < arr1.size() && j < arr2.size()) {
if (arr1[i] < arr2[j]) {
result.push_back(arr1[i++]);
} else {
result.push_back(arr2[j++]);
}
}
while (i < arr1.size()) {
result.push_back(arr1[i++]);
}
while (j < arr2.size()) {
result.push_back(arr2[j++]);
}
return result;
}
int main(){
std::vector<int> arr1 = {1, 3, 5, 7};
std::vector<int> arr2 = {2, 4, 6, 8};
std::vector<int> mergedArray = mergeSortedArrays(arr1, arr2);
std::cout << "Merged array: ";
for (int num : mergedArray) {
std::cout << num << " ";
}
return 0;
}

Python Implementation:

def merge_sorted_arrays(arr1, arr2):
merged_array = []
i, j = 0, 0
while i < len(arr1) and j < len(arr2):
if arr1[i] < arr2[j]:
merged_array.append(arr1[i])
i += 1
else:
merged_array.append(arr2[j])
j += 1
while i < len(arr1):
merged_array.append(arr1[i])
i += 1
while j < len(arr2):
merged_array.append(arr2[j])
j += 1
return merged_array
# Example usage:
arr1 = [1, 3, 5, 7]
arr2 = [2, 4, 6, 8]
print(f"Merged array: {merge_sorted_arrays(arr1, arr2)}")

26. Find the Intersection of Two Arrays

C++ Implementation:

#include <iostream>

#include <vector>

#include <unordered_set>

std::vector<int> arrayIntersection(std::vector<int>& arr1, std::vector<int>& arr2) {

std::unordered_set<int> set1(arr1.begin(), arr1.end());
std::vector<int> intersection;
for (int num : arr2) {
if (set1.find(num) != set1.end()) {
intersection.push_back(num);
set1.erase(num); // To avoid duplicates
}
}
return intersection;
}
int main() {
std::vector<int> arr1 = {1, 2, 2, 3, 4};
std::vector<int> arr2 = {2, 2, 3, 5};
std::vector<int> result = arrayIntersection(arr1, arr2);
std::cout << "Intersection of arrays: ";
for (int num : result) {
std::cout << num << " ";
}
return 0;
}

Python Implementation:

def array_intersection(arr1, arr2):
set1 = set(arr1)
intersection = []
for num in arr2:
if num in set1:
intersection.append(num)
set1.remove(num) # To avoid duplicates
return intersection
# Example usage:

arr1 = [1, 2, 2, 3, 4]
arr2 = [2, 2, 3, 5]
print(f"Intersection of arrays: {array_intersection(arr1, arr2)}")

27. Find the Union of Two Arrays

C++ Implementation:

#include <iostream>

#include <vector>

#include <unordered_set>
std::vector<int> arrayUnion(std::vector<int>& arr1, std::vector<int>& arr2) {
std::unordered_set<int> unionSet(arr1.begin(), arr1.end());
for (int num : arr2) {
unionSet.insert(num);
}
return std::vector<int>(unionSet.begin(), unionSet.end());
}
int main() {
std::vector<int> arr1 = {1, 2, 3, 4};
std::vector<int> arr2 = {3, 4, 5, 6};
std::vector<int> result = arrayUnion(arr1, arr2);
std::cout << "Union of arrays: ";
for (int num : result) {
std::cout << num << " ";
}
return 0;
}

Python Implementation:

def array_union(arr1, arr2):
union_set = set(arr1).union(arr2)
return list(union_set)
# Example usage:

arr1 = [1, 2, 3, 4]
arr2 = [3, 4, 5, 6]
print(f"Union of arrays: {array_union(arr1, arr2)}")

28. Implement a Linked List

C++ Implementation:

#include <iostream>

class Node {

public:
int data;
Node* next;
Node(int data) {
this->data = data;
this->next = nullptr;
}
};
class LinkedList {
public:
Node* head;
LinkedList() { head = nullptr; }
void append(int data);
void display();
};
void LinkedList::append(int data) {
Node* newNode = new Node(data);
if (!head) {
head = newNode;
return;
}
Node* temp = head;
while (temp->next) {
temp = temp->next;
}
temp->next = newNode;
}
void LinkedList::display() {
Node* temp = head;
while (temp) {
std::cout << temp->data << " ";
temp = temp->next;
}
}
int main() {
LinkedList list;
list.append(10);
list.append(20);
list.append(30);
std::cout << "Linked list: ";
list.display();
return 0;
}

Python Implementation:

class Node:
def __init__(self, data):
self.data = data
self.next = None

class LinkedList:

def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if not self.head:
self.head = new_node
return
last = self.head
while last.next:
last = last.next
last.next = new_node
def display(self):
temp = self.head
while temp:
print(temp.data, end=" ")
temp = temp.next

# Example usage:


list = LinkedList()
list.append(10)
list.append(20)
list.append(30)
print("Linked list:", end=" ")
list.display()

29. Reverse a Linked List

C++ Implementation:

#include <iostream>

class Node {

public:
int data;
Node* next;
Node(int data) {
this->data = data;
this->next = nullptr;
}
};
class LinkedList {
public:
Node* head;
LinkedList() {
head = nullptr;
}
void append(int data);
void reverse();
void display();
};
void LinkedList::append(int data) {
Node* newNode = new Node(data);
if (!head) {
head = newNode;
return;
}
Node* temp = head;
while (temp->next) {
temp = temp->next;
}
temp->next = newNode;
}
void LinkedList::reverse() {
Node* prev = nullptr;
Node* curr = head;
Node* next = nullptr;
while (curr) {
next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
head = prev;
}
void LinkedList::display() {
Node* temp = head;
while (temp) {
std::cout << temp->data << " ";
temp = temp->next;
}
}
int main() {
LinkedList list;
list.append(10);
list.append(20);
list.append(30);
std::cout << "Original linked list: ";
list.display();
list.reverse();
std::cout << "\nReversed linked list: ";
list.display();
return 0;
}

techbloggerworld.com

Nagendra Kumar Sharma I Am Software engineer

Leave a Reply

Your email address will not be published. Required fields are marked *