[Go to site: main page, start]

0% found this document useful (0 votes)
3 views231 pages

String and Array Manipulation Functions

Uploaded by

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

String and Array Manipulation Functions

Uploaded by

ankitsingh991008
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

✅ 1.

Reverse a String
📌 Question:
Write a function that reverses a given string.

📥 Sample Input:
Input: "hello"

📤 Output:
Output: "olleh"

🧑‍💻 Java Code:


java

public String reverseString(String str) {


return new StringBuilder(str).reverse().toString();
}

👨‍💻 C Code:
c

#include <stdio.h>
#include <string.h>

void reverse(char* str) {


int i = 0, j = strlen(str) - 1;
while (i < j) {
char temp = str[i];
str[i++] = str[j];
str[j--] = temp;
}
}

int main() {
char str[] = "hello";
reverse(str);
printf("Reversed: %s\n", str);
return 0;
}

✅ 2. Find the Maximum Element in an Array


📌 Question:
Write a function that finds the maximum element in an array of integers.

📥 Sample Input:
Input: [3, 7, 1, 9, 2]

📤 Output:
Output: 9

🧑‍💻 Java Code:


java

public int findMax(int[] arr) {


int max = arr[0];
for (int num : arr) {
if (num > max) max = num;
}
return max;
}

👨‍💻 C Code:
c

#include <stdio.h>

int findMax(int arr[], int n) {


int max = arr[0];
for (int i = 1; i < n; i++) {
if (arr[i] > max)
max = arr[i];
}
return max;
}

int main() {
int arr[] = {3, 7, 1, 9, 2};
printf("Max: %d\n", findMax(arr, 5));
return 0;
}

✅ 3. Check if a String is a Palindrome


📌 Question:
Check if a string reads the same backward and forward.

📥 Sample Input:
Input: "madam"

📤 Output:
Output: true

🧑‍💻 Java Code:


java

public boolean isPalindrome(String str) {


int i = 0, j = [Link]() - 1;
while (i < j) {
if ([Link](i++) != [Link](j--)) return false;
}
return true;
}

👨‍💻 C Code:
c

#include <stdio.h>
#include <string.h>
#include <stdbool.h>

bool isPalindrome(char* str) {


int i = 0, j = strlen(str) - 1;
while (i < j) {
if (str[i++] != str[j--]) return false;
}
return true;
}

int main() {
char str[] = "madam";
printf("Palindrome: %s\n", isPalindrome(str) ? "true" :
"false");
return 0;
}

✅ 4. Find the Missing Number in an Array


📌 Question:
Given an array conta ng numbers from 1 to n with one number missing, find it.

📥 Sample Input:
Input: [1, 2, 4, 5], n = 5

📤 Output:
Output: 3

🧑‍💻 Java Code:


java

public int findMissing(int[] arr, int n) {


int total = n * (n + 1) / 2;
for (int num : arr) total -= num;
return total;
}
👨‍💻 C Code:
c

#include <stdio.h>

int findMissing(int arr[], int n) {


int total = n * (n + 1) / 2;
for (int i = 0; i < n - 1; i++) {
total -= arr[i];
}
return total;
}

int main() {
int arr[] = {1, 2, 4, 5};
printf("Missing: %d\n", findMissing(arr, 5));
return 0;
}

✅ 5. Find the Intersection of Two Arrays


📌 Question:
Find elements present in both arrays.

📥 Sample Input:
Input: [1, 2, 4, 5], [2, 5, 6]

📤 Output:
Output: [2, 5]

🧑‍💻 Java Code:


java

public List<Integer> intersection(int[] a, int[] b) {


Set<Integer> setA = new HashSet<>();
Set<Integer> result = new HashSet<>();
for (int num : a) [Link](num);
for (int num : b) {
if ([Link](num)) [Link](num);
}
return new ArrayList<>(result);
}

👨‍💻 C Code:
c

#include <stdio.h>

void findIntersection(int a[], int b[], int n1, int n2) {


printf("Intersection: ");
for (int i = 0; i < n1; i++) {
for (int j = 0; j < n2; j++) {
if (a[i] == b[j]) {
printf("%d ", a[i]);
break;
}
}
}
printf("\n");
}

int main() {
int a[] = {1, 2, 4, 5}, b[] = {2, 5, 6};
findIntersection(a, b, 4, 3);
return 0;
}

✅ 6. Remove Duplicates from an Array


📌 Question:
Remove duplicates while preserving order.

📥 Sample Input:
Input: [1, 2, 2, 3, 1]

📤 Output:
Output: [1, 2, 3]

🧑‍💻 Java Code:


java

public int[] removeDuplicates(int[] arr) {


Set<Integer> seen = new LinkedHashSet<>();
for (int num : arr) [Link](num);
return [Link]().mapToInt(i -> i).toArray();
}
👨‍💻 C Code:
c

#include <stdio.h>
#include <stdbool.h>

void removeDuplicates(int arr[], int n) {


printf("Unique elements: ");
for (int i = 0; i < n; i++) {
bool isDuplicate = false;
for (int j = 0; j < i; j++) {
if (arr[i] == arr[j]) {
isDuplicate = true;
break;
}
}
if (!isDuplicate) {
printf("%d ", arr[i]);
}
}
printf("\n");
}

int main() {
int arr[] = {1, 2, 2, 3, 1};
removeDuplicates(arr, 5);
return 0;
}

✅ 7. Count Occurrences of Each Element


📌 Question:
Count how many times each number appears.

📥 Sample Input:
Input: [1, 2, 2, 3, 1]

📤 Output:
Output: 1->2, 2->2, 3->1

🧑‍💻 Java Code:


java

public void countOccurrences(int[] arr) {


Map<Integer, Integer> map = new HashMap<>();
for (int num : arr) {
[Link](num, [Link](num, 0) + 1);
}
for ([Link]<Integer, Integer> entry : [Link]()) {
[Link]([Link]() + " -> " +
[Link]());
}
}

👨‍💻 C Code:
c

#include <stdio.h>

void countOccurrences(int arr[], int n) {


for (int i = 0; i < n; i++) {
int count = 1, flag = 0;
for (int j = 0; j < i; j++) {
if (arr[i] == arr[j]) {
flag = 1;
break;
}
}
if (flag) continue;
for (int j = i + 1; j < n; j++) {
if (arr[i] == arr[j]) count++;
}
printf("%d -> %d\n", arr[i], count);
}
}

int main() {
int arr[] = {1, 2, 2, 3, 1};
countOccurrences(arr, 5);
return 0;
}

✅ 8. Find the Second Largest Element


📌 Question:
Find the second highest number.

📥 Sample Input:
Input: [4, 7, 2, 9, 5]

📤 Output:
Output: 7

🧑‍💻 Java Code:


java

public int secondLargest(int[] arr) {


int max = Integer.MIN_VALUE, second = Integer.MIN_VALUE;
for (int num : arr) {
if (num > max) {
second = max;
max = num;
} else if (num > second && num != max) {
second = num;
}
}
return second;
}

👨‍💻 C Code:
c

#include <stdio.h>

int secondLargest(int arr[], int n) {


int max = arr[0], second = -1;
for (int i = 1; i < n; i++) {
if (arr[i] > max) {
second = max;
max = arr[i];
} else if (arr[i] > second && arr[i] != max) {
second = arr[i];
}
}
return second;
}

int main() {
int arr[] = {4, 7, 2, 9, 5};
printf("Second Largest: %d\n", secondLargest(arr, 5));
return 0;
}

✅ 9. Merge Two Sorted Arrays


📌 Question:
Merge two sorted arrays into one sorted array.

📥 Sample Input:
Input: A = [1, 3, 5], B = [2, 4, 6]

📤 Output:
Output: [1, 2, 3, 4, 5, 6]

🧑‍💻 Java Code:


java

public int[] mergeSorted(int[] A, int[] B) {


int[] result = new int[[Link] + [Link]];
int i = 0, j = 0, k = 0;
while (i < [Link] && j < [Link]) {
result[k++] = (A[i] < B[j]) ? A[i++] : B[j++];
}

while (i < [Link]) result[k++] = A[i++];


while (j < [Link]) result[k++] = B[j++];

return result;
}

👨‍💻 C Code:
c

#include <stdio.h>

void mergeSorted(int A[], int B[], int n, int m) {


int result[n + m], i = 0, j = 0, k = 0;

while (i < n && j < m) {


result[k++] = (A[i] < B[j]) ? A[i++] : B[j++];
}

while (i < n) result[k++] = A[i++];


while (j < m) result[k++] = B[j++];

printf("Merged: ");
for (int x = 0; x < n + m; x++) printf("%d ", result[x]);
printf("\n");
}

int main() {
int A[] = {1, 3, 5}, B[] = {2, 4, 6};
mergeSorted(A, B, 3, 3);
return 0;
}

✅ 10. Length of the Longest Substring Without


Repeating Characters
📌 Question:
Find length of longest substring without duplicate characters.

📥 Sample Input:
Input: "abcabcbb"

📤 Output:
Output: 3

🧑‍💻 Java Code:


java

public int longestUniqueSubstring(String s) {


Set<Character> set = new HashSet<>();
int maxLen = 0, left = 0;

for (int right = 0; right < [Link](); right++) {


while ([Link]([Link](right))) {
[Link]([Link](left++));
}
[Link]([Link](right));
maxLen = [Link](maxLen, right - left + 1);
}

return maxLen;
}

👨‍💻 C Code:
c

#include <stdio.h>
#include <string.h>

int longestUniqueSubstring(char* str) {


int maxLen = 0, start = 0;
int index[256];
for (int i = 0; i < 256; i++) index[i] = -1;

for (int end = 0; str[end]; end++) {


if (index[str[end]] >= start)
start = index[str[end]] + 1;

index[str[end]] = end;
int len = end - start + 1;
if (len > maxLen) maxLen = len;
}
return maxLen;
}

int main() {
char str[] = "abcabcbb";
printf("Longest Unique Substring Length: %d\n",
longestUniqueSubstring(str));
return 0;
}
✅ 11. Reverse a Linked List
📌 Question:
Reverse a singly linked list.

📥 Sample Input:
Input: 1 → 2 → 3 → 4

📤 Output:
Output: 4 → 3 → 2 → 1

🧑‍💻 Java Code:


java

class Node {
int data;
Node next;
Node(int data) { [Link] = data; }
}

public Node reverse(Node head) {


Node prev = null;
while (head != null) {
Node next = [Link];
[Link] = prev;
prev = head;
head = next;
}
return prev;
}

👨‍💻 C Code:
c

#include <stdio.h>
#include <stdlib.h>

struct Node {
int data;
struct Node* next;
};

struct Node* reverse(struct Node* head) {


struct Node *prev = NULL, *next = NULL;
while (head) {
next = head->next;
head->next = prev;
prev = head;
head = next;
}
return prev;
}

void printList(struct Node* head) {


while (head) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
struct Node* newNode(int data) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->data = data;
node->next = NULL;
return node;
}

int main() {
struct Node* head = newNode(1);
head->next = newNode(2);
head->next->next = newNode(3);
head = reverse(head);
printList(head);
return 0;
}

✅ 12. Implement Stack Using Array


📌 Question:
Implement a stack with push, pop, and peek.

📥 Sample Input:
Push 1, Push 2, Pop

📤 Output:
Popped: 2

🧑‍💻 Java Code:


java

class Stack {
int[] arr;
int top = -1;

Stack(int size) {
arr = new int[size];
}

void push(int x) {
if (top == [Link] - 1) throw new
RuntimeException("Overflow");
arr[++top] = x;
}

int pop() {
if (top == -1) throw new RuntimeException("Underflow");
return arr[top--];
}

int peek() {
return arr[top];
}

boolean isEmpty() {
return top == -1;
}
}

👨‍💻 C Code:
c

#include <stdio.h>
#define MAX 100

int stack[MAX], top = -1;

void push(int x) {
if (top == MAX - 1) {
printf("Stack Overflow\n");
return;
}
stack[++top] = x;
}

int pop() {
if (top == -1) {
printf("Stack Underflow\n");
return -1;
}
return stack[top--];
}

int peek() {
return (top != -1) ? stack[top] : -1;
}

int main() {
push(1);
push(2);
printf("Popped: %d\n", pop());
return 0;
}

✅ 13. Implement a Queue Using an Array


📌 Question:
Implement a queue with the following operations:

●​ enqueue(x) – adds x to the queue​

●​ dequeue() – removes an element from the front​

●​ peek() – returns the front element​

●​ isEmpty() – checks if the queue is empty​

🧠 Explanation:
A queue follows the FIFO (First-In-First-Out) principle. We use an array and two pointers:

●​ front for removing elements​

●​ rear for inserting elements​


We use a circular approach to avoid wasting space.​

📥 Sample Input:
s

enqueue(10)
enqueue(20)
dequeue()
enqueue(30)
peek()

📤 Expected Output:
s

10 (removed)
30 (front element)
🧑‍💻 Java Code:
java

class Queue {
int[] arr;
int front, rear, size;

Queue(int capacity) {
arr = new int[capacity];
front = 0;
rear = -1;
size = 0;
}

void enqueue(int x) {
if (size == [Link]) {
[Link]("Queue Full");
return;
}
rear = (rear + 1) % [Link];
arr[rear] = x;
size++;
}

int dequeue() {
if (size == 0) {
[Link]("Queue Empty");
return -1;
}
int result = arr[front];
front = (front + 1) % [Link];
size--;
return result;
}

int peek() {
if (size == 0) return -1;
return arr[front];
}

boolean isEmpty() {
return size == 0;
}
}

👨‍💻 C Code:
c

#include <stdio.h>
#define SIZE 100

int queue[SIZE];
int front = 0, rear = -1, count = 0;

void enqueue(int x) {
if (count == SIZE) {
printf("Queue Full\n");
return;
}
rear = (rear + 1) % SIZE;
queue[rear] = x;
count++;
}
int dequeue() {
if (count == 0) {
printf("Queue Empty\n");
return -1;
}
int result = queue[front];
front = (front + 1) % SIZE;
count--;
return result;
}

int peek() {
if (count == 0) return -1;
return queue[front];
}

int main() {
enqueue(10);
enqueue(20);
printf("Dequeued: %d\n", dequeue()); // 10
enqueue(30);
printf("Front element: %d\n", peek()); // 20
return 0;
}

✅ 14. Find the Lowest Common Ancestor (LCA) in a


Binary Tree
📌 Question:
Given a binary tree and two nodes p and q, find the Lowest Common Ancestor (LCA) of
the two nodes.
🧠 Explanation:
The Lowest Common Ancestor of two nodes p and q in a binary tree is the lowest
(deepest) node that has both p and q as descendants (where a node can be a descendant
of itself).

●​ If one node is on the left subtree and another on the right, the current node is the
LCA.​

●​ If both are on the same side, go deeper into that side.​

📥 Sample Input:
A binary tree:

3
/ \
5 1
/ \ / \
6 2 0 8

Find LCA of 5 and 1

📤 Expected Output:
makefile

Output: 3

🧑‍💻 Java Code:


java

class TreeNode {
int val;
TreeNode left, right;
TreeNode(int x) { val = x; }
}

class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p,
TreeNode q) {
if (root == null || root == p || root == q) return root;

TreeNode left = lowestCommonAncestor([Link], p, q);


TreeNode right = lowestCommonAncestor([Link], p, q);

if (left != null && right != null) return root;


return (left != null) ? left : right;
}
}

👨‍💻 C Code:
c

#include <stdio.h>
#include <stdlib.h>

typedef struct TreeNode {


int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;

TreeNode* newNode(int val) {


TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = node->right = NULL;
return node;
}

TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p,


TreeNode* q) {
if (!root || root == p || root == q) return root;

TreeNode* left = lowestCommonAncestor(root->left, p, q);


TreeNode* right = lowestCommonAncestor(root->right, p, q);

if (left && right) return root;


return (left != NULL) ? left : right;
}

int main() {
TreeNode* root = newNode(3);
root->left = newNode(5);
root->right = newNode(1);
root->left->left = newNode(6);
root->left->right = newNode(2);
root->right->left = newNode(0);
root->right->right = newNode(8);

TreeNode* lca = lowestCommonAncestor(root, root->left,


root->right);
printf("LCA: %d\n", lca->val); // Output: 3
return 0;
}

✅ 15. Check if a Binary Tree is a Binary Search Tree


(BST)
📌 Question:
Write a function to check whether a given binary tree is a Binary Search Tree (BST).

🧠 Explanation:
A Binary Search Tree (BST) is a binary tree where:

●​ All nodes in the left subtree are less than the root.​

●​ All nodes in the right subtree are greater than the root.​

●​ This rule is recursively true for all subtrees.​

We use inorder traversal or check with min-max bounds.

📥 Sample Input:
10
/ \
5 15

📤 Output:
pgsql

True (Valid BST)

🧑‍💻 Java Code:


java

class TreeNode {
int val;
TreeNode left, right;
TreeNode(int x) { val = x; }
}

class Solution {
public boolean isBST(TreeNode root) {
return helper(root, Long.MIN_VALUE, Long.MAX_VALUE);
}

private boolean helper(TreeNode node, long min, long max) {


if (node == null) return true;
if ([Link] <= min || [Link] >= max) return false;
return helper([Link], min, [Link]) &&
helper([Link], [Link], max);
}
}

👨‍💻 C Code:
c

#include <stdio.h>
#include <limits.h>
#include <stdlib.h>

typedef struct TreeNode {


int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;

TreeNode* newNode(int val) {


TreeNode* node = (TreeNode*)malloc(sizeof(TreeNode));
node->val = val;
node->left = node->right = NULL;
return node;
}

int isBSTUtil(TreeNode* node, int min, int max) {


if (node == NULL) return 1;
if (node->val <= min || node->val >= max) return 0;
return isBSTUtil(node->left, min, node->val) &&
isBSTUtil(node->right, node->val, max);
}

int isBST(TreeNode* root) {


return isBSTUtil(root, INT_MIN, INT_MAX);
}

✅ 16. Level Order Traversal of Binary Tree


📌 Question:
Perform a level-order (breadth-first) traversal of a binary tree and print elements level by
level.

🧠 Explanation:
Use a queue to process nodes level by level from the root.

📥 Sample Input:
1
/ \
2 3
📤 Output:
1 2 3

🧑‍💻 Java Code:


java

import [Link].*;

class TreeNode {
int val;
TreeNode left, right;
TreeNode(int x) { val = x; }
}

class Solution {
public void levelOrder(TreeNode root) {
if (root == null) return;
Queue<TreeNode> q = new LinkedList<>();
[Link](root);

while (![Link]()) {
TreeNode curr = [Link]();
[Link]([Link] + " ");
if ([Link] != null) [Link]([Link]);
if ([Link] != null) [Link]([Link]);
}
}
}

👨‍💻 C Code:
c

#include <stdio.h>
#include <stdlib.h>

typedef struct TreeNode {


int val;
struct TreeNode* left;
struct TreeNode* right;
} TreeNode;

typedef struct Queue {


TreeNode* data[100];
int front, rear;
} Queue;

void enqueue(Queue* q, TreeNode* node) {


q->data[++q->rear] = node;
}

TreeNode* dequeue(Queue* q) {
return q->data[q->front++];
}

int isEmpty(Queue* q) {
return q->front > q->rear;
}

void levelOrder(TreeNode* root) {


if (!root) return;
Queue q = {.front = 0, .rear = -1};
enqueue(&q, root);
while (!isEmpty(&q)) {
TreeNode* temp = dequeue(&q);
printf("%d ", temp->val);
if (temp->left) enqueue(&q, temp->left);
if (temp->right) enqueue(&q, temp->right);
}
}

✅ 17. Clone a Linked List with Random Pointers


📌 Question:
Given a linked list where each node has two pointers:

●​ next pointer to the next node​

●​ random pointer that can point to any node in the list or NULL​

Write a function to create a deep copy of the list.

🧠 Explanation:
We need to clone:

1.​ The structure of the list (via next)​

2.​ The random pointers for each node​

🧩 Approach:
●​ Use a hashmap to store original node → cloned node mapping​

●​ Traverse again to fix next and random using the map​

📥 Sample Input:
Original Linked List:
s

Node1(val=1, random=Node3) → Node2(val=2, random=Node1) →


Node3(val=3, random=NULL)

📤 Output:
Cloned Linked List (deep copy):

Node1(val=1, random=Node3) → Node2(val=2, random=Node1) →


Node3(val=3, random=NULL)

🧑‍💻 Java Code:


java

import [Link];

class Node {
int val;
Node next, random;
Node(int val) { [Link] = val; }
}

public class CloneLinkedList {


public Node cloneList(Node head) {
if (head == null) return null;

HashMap<Node, Node> map = new HashMap<>();

Node current = head;


while (current != null) {
[Link](current, new Node([Link]));
current = [Link];
}

current = head;
while (current != null) {
[Link](current).next = [Link]([Link]);
[Link](current).random = [Link]([Link]);
current = [Link];
}

return [Link](head);
}
}

👨‍💻 C Code:
c

#include <stdio.h>
#include <stdlib.h>

typedef struct Node {


int val;
struct Node* next;
struct Node* random;
} Node;

// Create a new node


Node* createNode(int val) {
Node* node = (Node*)malloc(sizeof(Node));
node->val = val;
node->next = NULL;
node->random = NULL;
return node;
}

// Use hashmap-like structure with extra node links for simplicity


in C
Node* cloneList(Node* head) {
if (!head) return NULL;

// Step 1: Insert cloned nodes after each original node


Node* curr = head;
while (curr) {
Node* copy = createNode(curr->val);
copy->next = curr->next;
curr->next = copy;
curr = copy->next;
}

// Step 2: Set random pointers


curr = head;
while (curr) {
if (curr->random)
curr->next->random = curr->random->next;
curr = curr->next->next;
}

// Step 3: Separate original and cloned list


Node* dummy = createNode(0);
Node* copy = dummy;
curr = head;
while (curr) {
copy->next = curr->next;
curr->next = curr->next->next;

copy = copy->next;
curr = curr->next;
}

return dummy->next;
}

✅ 18. Find the Kth Largest Element in an Array


📌 Question:
Given an array of integers and an integer K, write a function to return the Kth largest
element in the array.

🧠 Explanation:
●​ You are given an unsorted array.​

●​ The Kth largest element means the element that would appear in the Kth position
from the end if the array were sorted in descending order.​

🧩 Approaches:
●​ Sort the array and return arr[n - k]​

●​ Use a min-heap of size K (more efficient for large arrays)​

📥 Sample Input:
arr = [3, 2, 1, 5, 6, 4], K = 2

📤 Output:
s

5 (The 2nd largest element)


🧑‍💻 Java Code (Using Sorting for Simplicity):
java

import [Link];

public class KthLargest {


public int findKthLargest(int[] nums, int k) {
[Link](nums);
return nums[[Link] - k];
}

public static void main(String[] args) {


KthLargest obj = new KthLargest();
int[] arr = {3, 2, 1, 5, 6, 4};
[Link]([Link](arr, 2)); // Output: 5
}
}

👨‍💻 C Code (Using Sorting):


c

#include <stdio.h>
#include <stdlib.h>

int compare(const void* a, const void* b) {


return (*(int*)a - *(int*)b);
}

int findKthLargest(int arr[], int n, int k) {


qsort(arr, n, sizeof(int), compare);
return arr[n - k];
}

int main() {
int arr[] = {3, 2, 1, 5, 6, 4};
int n = sizeof(arr) / sizeof(arr[0]);
int k = 2;
printf("Kth largest element: %d\n", findKthLargest(arr, n, k));
// Output: 5
return 0;
}

✅ 19. Find All Combinations of a Sum


📌 Question:
Given an array of positive integers and a target sum, find all unique combinations of
numbers where the sum equals the target.

●​ Each number in the array may be used multiple times.​

●​ Return all distinct combinations.​

🧠 Explanation:
This is a combinatorics + backtracking problem:

●​ Try each number recursively.​

●​ Include it or skip it.​

●​ When the sum becomes 0, we found a valid combination.​

📥 Sample Input:
arr = [2, 3, 6, 7], target = 7

📤 Output:
[ [2, 2, 3], [7] ]

🧑‍💻 Java Code:


java

import [Link].*;

public class CombinationSum {


public List<List<Integer>> combinationSum(int[] candidates, int
target) {
List<List<Integer>> result = new ArrayList<>();
backtrack(candidates, 0, target, new ArrayList<>(), result);
return result;
}

private void backtrack(int[] arr, int index, int target,


List<Integer> curr, List<List<Integer>> res) {
if (target == 0) {
[Link](new ArrayList<>(curr));
return;
}
if (target < 0 || index == [Link]) return;

// Include current number


[Link](arr[index]);
backtrack(arr, index, target - arr[index], curr, res);
[Link]([Link]() - 1); // backtrack

// Skip current number


backtrack(arr, index + 1, target, curr, res);
}

public static void main(String[] args) {


CombinationSum obj = new CombinationSum();
int[] arr = {2, 3, 6, 7};
List<List<Integer>> ans = [Link](arr, 7);
[Link](ans);
}
}

👨‍💻 C Code (Simplified, Prints Result):


c

#include <stdio.h>

void printCombination(int arr[], int n, int index, int target, int


data[], int depth) {
if (target == 0) {
for (int i = 0; i < depth; i++)
printf("%d ", data[i]);
printf("\n");
return;
}
if (target < 0 || index >= n) return;

// Include current element


data[depth] = arr[index];
printCombination(arr, n, index, target - arr[index], data, depth
+ 1);
// Exclude current element
printCombination(arr, n, index + 1, target, data, depth);
}

int main() {
int arr[] = {2, 3, 6, 7};
int target = 7;
int data[100];
int n = sizeof(arr) / sizeof(arr[0]);
printf("Combinations that sum to %d:\n", target);
printCombination(arr, n, 0, target, data, 0);
return 0;
}

✅ 20. Binary Operations on Strings (AND, OR, XOR)


📌 Question:
Write a function that takes two binary strings and performs bitwise operations on them:

●​ AND​

●​ OR​

●​ XOR​

Each operation should return a new binary string of the same length as the inputs.

🧠 Explanation:
To apply bitwise operations on strings:

1.​ Compare corresponding characters in both strings.​

2.​ Apply the chosen operation (AND, OR, XOR) character by character.​
Ensure both binary strings are of the same length.

📥 Sample Input:
Binary1 = "1101"
Binary2 = "1011"

📤 Output:
vbnet

AND : "1001"
OR : "1111"
XOR : "0110"

🧑‍💻 Java Code:


java

public class BinaryOps {

public static String binaryAnd(String a, String b) {


StringBuilder sb = new StringBuilder();
for (int i = 0; i < [Link](); i++)
[Link](([Link](i) == '1' && [Link](i) == '1') ?
'1' : '0');
return [Link]();
}

public static String binaryOr(String a, String b) {


StringBuilder sb = new StringBuilder();
for (int i = 0; i < [Link](); i++)
[Link](([Link](i) == '1' || [Link](i) == '1') ?
'1' : '0');
return [Link]();
}

public static String binaryXor(String a, String b) {


StringBuilder sb = new StringBuilder();
for (int i = 0; i < [Link](); i++)
[Link](([Link](i) != [Link](i)) ? '1' : '0');
return [Link]();
}

public static void main(String[] args) {


String a = "1101";
String b = "1011";

[Link]("AND : " + binaryAnd(a, b)); // 1001


[Link]("OR : " + binaryOr(a, b)); // 1111
[Link]("XOR : " + binaryXor(a, b)); // 0110
}
}

👨‍💻 C Code:
c

#include <stdio.h>
#include <string.h>

void binaryOps(char* a, char* b) {


int len = strlen(a);
char andResult[len+1], orResult[len+1], xorResult[len+1];

for (int i = 0; i < len; i++) {


andResult[i] = (a[i] == '1' && b[i] == '1') ? '1' : '0';
orResult[i] = (a[i] == '1' || b[i] == '1') ? '1' : '0';
xorResult[i] = (a[i] != b[i]) ? '1' : '0';
}

andResult[len] = orResult[len] = xorResult[len] = '\0';

printf("AND : %s\n", andResult);


printf("OR : %s\n", orResult);
printf("XOR : %s\n", xorResult);
}

int main() {
char a[] = "1101";
char b[] = "1011";
binaryOps(a, b);
return 0;
}

✅ 21. Calculate Binary Operations from a String


Expression
📌 Question:
Given a string expression like:

arduino

"1010 AND 0110 OR 1111"

Evaluate the expression from left to right, applying each binary operation sequentially.

🧠 Explanation:
●​ Split the string by spaces.​

●​ Start from the leftmost binary string.​

●​ For each operation (AND, OR, XOR), apply it with the next binary string.​

●​ Continue until the end.​

✅ Note: Do not follow traditional precedence rules—evaluate strictly from left to right.

📥 Sample Input:
Input: "1010 AND 0110 OR 1111"

📤 Output:
Result: 1111

📚 Explanation:

Step 1: 1010 AND 0110 = 0010


Step 2: 0010 OR 1111 = 1111

🧑‍💻 Java Code:


java

public class BinaryCalculator {

public static String applyOp(String a, String b, String op) {


StringBuilder sb = new StringBuilder();
for (int i = 0; i < [Link](); i++) {
switch (op) {
case "AND":
[Link](([Link](i) == '1' && [Link](i) ==
'1') ? '1' : '0');
break;
case "OR":
[Link](([Link](i) == '1' || [Link](i) ==
'1') ? '1' : '0');
break;
case "XOR":
[Link](([Link](i) != [Link](i)) ? '1' :
'0');
break;
}
}
return [Link]();
}

public static String evaluate(String expr) {


String[] tokens = [Link](" ");
String result = tokens[0];
for (int i = 1; i < [Link] - 1; i += 2) {
String op = tokens[i];
String next = tokens[i + 1];
result = applyOp(result, next, op);
}
return result;
}

public static void main(String[] args) {


String input = "1010 AND 0110 OR 1111";
[Link]("Result: " + evaluate(input)); // Output:
1111
}
}

👨‍💻 C Code:
c

#include <stdio.h>
#include <string.h>

void binaryOp(char* a, char* b, char* op, char* result) {


for (int i = 0; a[i]; i++) {
if (strcmp(op, "AND") == 0)
result[i] = (a[i] == '1' && b[i] == '1') ? '1' : '0';
else if (strcmp(op, "OR") == 0)
result[i] = (a[i] == '1' || b[i] == '1') ? '1' : '0';
else if (strcmp(op, "XOR") == 0)
result[i] = (a[i] != b[i]) ? '1' : '0';
}
result[strlen(a)] = '\0';
}

int main() {
char expr[] = "1010 AND 0110 OR 1111";
char tokens[5][20];
int tokenCount = 0;
char* tok = strtok(expr, " ");
while (tok != NULL) {
strcpy(tokens[tokenCount++], tok);
tok = strtok(NULL, " ");
}

char result[20];
strcpy(result, tokens[0]);

for (int i = 1; i < tokenCount - 1; i += 2) {


char temp[20];
binaryOp(result, tokens[i + 1], tokens[i], temp);
strcpy(result, temp);
}

printf("Result: %s\n", result); // Output: 1111


return 0;
}

✅ 22. Find the Maximum and Its Index in an Array


📌 Question:
Write a function that finds the maximum number in an array and returns both the value and
its index.

🧠 Explanation:
●​ Traverse the array once.​

●​ Keep track of the maximum value and its index.​

●​ If the same max occurs multiple times, return the first one.​

📥 Sample Input:
arr = [3, 5, 2, 9, 7]
📤 Output:
makefile

Maximum: 9
Index: 3

🧑‍💻 Java Code:


java

public class MaxElementWithIndex {


public static void findMax(int[] arr) {
int max = arr[0];
int index = 0;
for (int i = 1; i < [Link]; i++) {
if (arr[i] > max) {
max = arr[i];
index = i;
}
}
[Link]("Maximum: " + max);
[Link]("Index: " + index);
}

public static void main(String[] args) {


int[] arr = {3, 5, 2, 9, 7};
findMax(arr);
}
}

👨‍💻 C Code:
c
#include <stdio.h>

void findMax(int arr[], int n) {


int max = arr[0];
int index = 0;
for (int i = 1; i < n; i++) {
if (arr[i] > max) {
max = arr[i];
index = i;
}
}
printf("Maximum: %d\n", max);
printf("Index: %d\n", index);
}

int main() {
int arr[] = {3, 5, 2, 9, 7};
int n = sizeof(arr) / sizeof(arr[0]);
findMax(arr, n);
return 0;
}

✅ 23. differenceOfSum(n, m)
🧠 Explanation:
Find:

●​ Sum of numbers from 1 to n divisible by m​

●​ Sum of numbers not divisible by m​

●​ Return absolute difference between the two​

📥 Example:
Input: n = 30, m = 6
Divisible by 6: 6 + 12 + 18 + 24 + 30 = 90
Not divisible: 1+2+3+4+5+7+8+9... = 375
Output: |375 - 90| = 285

Java:
java

public class DifferenceOfSum {


public static int differenceOfSum(int n, int m) {
int divSum = 0, nonDivSum = 0;
for (int i = 1; i <= n; i++) {
if (i % m == 0)
divSum += i;
else
nonDivSum += i;
}
return [Link](divSum - nonDivSum);
}

public static void main(String[] args) {


[Link](differenceOfSum(30, 6)); // Output: 285
}
}

C:
c

#include <stdio.h>
#include <stdlib.h>
int differenceOfSum(int n, int m) {
int divSum = 0, nonDivSum = 0;
for (int i = 1; i <= n; i++) {
if (i % m == 0)
divSum += i;
else
nonDivSum += i;
}
return abs(divSum - nonDivSum);
}

int main() {
printf("%d\n", differenceOfSum(30, 6)); // Output: 285
return 0;
}

✅ 24. Find the Second Largest in Array of 1000 Elements


🧠 Explanation:
●​ Traverse once for max and second max​

●​ Return -1 if all elements are the same​

Java:
java

public class SecondLargest {


public static int findSecondLargest(int[] arr) {
int max = Integer.MIN_VALUE, second = -1;
for (int num : arr) {
if (num > max) {
second = max;
max = num;
} else if (num > second && num != max) {
second = num;
}
}
return second == Integer.MIN_VALUE ? -1 : second;
}
}

C:
c

int findSecondLargest(int arr[], int n) {


int max = -1e9, second = -1;
for (int i = 0; i < n; i++) {
if (arr[i] > max) {
second = max;
max = arr[i];
} else if (arr[i] > second && arr[i] != max) {
second = arr[i];
}
}
return (second == -1e9) ? -1 : second;
}

✅ 25. Charity Coins: Sum of Squares from 1 to x


📥 Input:
makefile

x = 3
Output: 1² + 2² + 3² = 14

Java:
java

public class Charity {


public static int coins(int x) {
int sum = 0;
for (int i = 1; i <= x; i++) {
sum += i * i;
}
return sum;
}
}

C:
c

int coins(int x) {
int sum = 0;
for (int i = 1; i <= x; i++)
sum += i * i;
return sum;
}

✅ 4. Sum of Divisors of a Number


📥 Input:

N = 6 → Divisors: 1, 2, 3, 6 → Output = 12
Java:
java

public class Divisors {


public static int sumOfDivisors(int n) {
int sum = 0;
for (int i = 1; i <= n; i++)
if (n % i == 0) sum += i;
return sum;
}
}

C:
c

int sumOfDivisors(int n) {
int sum = 0;
for (int i = 1; i <= n; i++)
if (n % i == 0) sum += i;
return sum;
}

✅ 26. Largest Number from Permutation of Array Elements


🧠 Explanation:
●​ Convert integers to strings​

●​ Sort with a custom comparator​

●​ Concatenate to form the largest number​


📥 Input:

[9, 91, 34] → Output: 99134

Java:
java

import [Link].*;

public class LargestNumber {


public static String largestNumber(int[] nums) {
String[] arr = new String[[Link]];
for (int i = 0; i < [Link]; i++)
arr[i] = [Link](nums[i]);

[Link](arr, (a, b) -> (b + a).compareTo(a + b));

if (arr[0].equals("0")) return "0";


StringBuilder sb = new StringBuilder();
for (String s : arr) [Link](s);
return [Link]();
}
}

✅27 SmallLargeSum Function


📌 Question Recap:
You are given an array of unique integers.​
Write a function to:

●​ Find the second largest element from even indices (0, 2, 4…)​
●​ Find the second largest element from odd indices (1, 3, 5…)​

●​ Return their sum​

Rules:

●​ Return 0 if array is empty or has ≤ 3 elements​

●​ All values are unique​

📥 Sample Input:
Input:

3 2 1 7 5 4

Even indices: 3, 1, 5 → second largest = 3

Odd indices: 2, 7, 4 → second largest = 4

Output: 3 + 4 = 7

🧑‍💻 Java Code:


import [Link].*;

public class SmallLargeSum {

public static int smallLargeSum(int[] arr) {


if (arr == null || [Link] <= 3)

return 0;

List<Integer> even = new ArrayList<>();

List<Integer> odd = new ArrayList<>();

for (int i = 0; i < [Link]; i++) {

if (i % 2 == 0) [Link](arr[i]);

else [Link](arr[i]);

[Link](even, [Link]());

[Link](odd, [Link]());

if ([Link]() < 2 || [Link]() < 2) return 0;

return [Link](1) + [Link](1); // second largest

public static void main(String[] args) {

int[] arr = {3, 2, 1, 7, 5, 4};

[Link](smallLargeSum(arr)); // Output: 7

}
👨‍💻 C Code:
#include <stdio.h>

void sortDescending(int arr[], int n) {

for (int i = 0; i < n-1; i++)

for (int j = i+1; j < n; j++)

if (arr[i] < arr[j]) {

int temp = arr[i];

arr[i] = arr[j];

arr[j] = temp;

int smallLargeSum(int arr[], int n) {

if (n <= 3) return 0;

int even[500], odd[500];

int e = 0, o = 0;

for (int i = 0; i < n; i++) {

if (i % 2 == 0) even[e++] = arr[i];
else odd[o++] = arr[i];

if (e < 2 || o < 2) return 0;

sortDescending(even, e);

sortDescending(odd, o);

return even[1] + odd[1]; // second largest from each

int main() {

int arr[] = {3, 2, 1, 7, 5, 4};

int n = sizeof(arr) / sizeof(arr[0]);

printf("%d\n", smallLargeSum(arr, n)); // Output: 7

return 0;

✅28 Question: CheckPassword


📌 Problem Statement:
Write a function CheckPassword(str) which accepts a string and validates a password
based on the following rules. It should return 1 if the password is valid, otherwise 0.

✅ Conditions for a Valid Password:


1.​ Must be at least 4 characters long.​

2.​ Must contain at least one digit (0–9).​

3.​ Must contain at least one uppercase letter (A–Z).​

4.​ Must not contain a space (' ') or a slash ('/').​

5.​ First character must not be a digit.​

📥 Sample Input:
makefile

Input: bB1_89

Output: 1

🧠 Explanation:
●​ ✅ Length = 6 → valid​
●​ ✅ Contains digit = 1​
●​ ✅ Contains uppercase = B​
●​ ✅ No space or slash​
●​ ✅ First character = b → not a digit​
➡️ All conditions met, so output is 1.​

👨‍💻 Java Code:


java
public class PasswordCheck {

public static int CheckPassword(String str) {

if ([Link]() < 4)

return 0;

if ([Link]([Link](0)))

return 0;

boolean hasDigit = false, hasUpper = false;

for (char ch : [Link]()) {

if ([Link](ch)) hasDigit = true;

if ([Link](ch)) hasUpper = true;

if (ch == ' ' || ch == '/') return 0;

return (hasDigit && hasUpper) ? 1 : 0;

public static void main(String[] args) {

[Link](CheckPassword("bB1_89")); // Output: 1

[Link](CheckPassword("1bB_89")); // Output: 0
[Link](CheckPassword("bb_89")); // Output: 0

👨‍💻 C Code:
c

#include <stdio.h>

#include <ctype.h>

#include <string.h>

int CheckPassword(char *str) {

int len = strlen(str);

if (len < 4) return 0;

if (isdigit(str[0])) return 0;

int hasDigit = 0, hasUpper = 0;

for (int i = 0; i < len; i++) {

if (isdigit(str[i])) hasDigit = 1;

if (isupper(str[i])) hasUpper = 1;

if (str[i] == ' ' || str[i] == '/') return 0;

}
return (hasDigit && hasUpper) ? 1 : 0;

int main() {

printf("%d\n", CheckPassword("bB1_89")); // Output: 1

printf("%d\n", CheckPassword("1bB_89")); // Output: 0

printf("%d\n", CheckPassword("bb_89")); // Output: 0

return 0;

✅ 29 Question: FindMaxInArray
📌 Problem Statement:
Write a function FindMaxInArray(array) which:

●​ Accepts an array of integers.​

●​ Finds the greatest number in the array.​

●​ Prints the number and its index on separate lines.​

📥 Sample Input:
makefile

Size: 10

Array: 15 78 96 17 20 65 14 36 18 20
📤 Output:
96

✅ Explanation:​
96 is the greatest number and its index in the array is 2 (0-based indexing).

👨‍💻 Java Code:


java

import [Link];

public class FindMaxInArray {

public static void main(String[] args) {

Scanner sc = new Scanner([Link]);

int n = [Link](); // Read size of array

int[] arr = new int[n];

// Read array values

for (int i = 0; i < n; i++) {

arr[i] = [Link]();

}
// Find max value and its index

int max = arr[0];

int index = 0;

for (int i = 1; i < n; i++) {

if (arr[i] > max) {

max = arr[i];

index = i;

// Output

[Link](max);

[Link](index);

👨‍💻 C Code:
c

#include <stdio.h>

int main() {

int n;
scanf("%d", &n); // Read size of array

int arr[n];

for (int i = 0; i < n; i++) {

scanf("%d", &arr[i]); // Read array elements

int max = arr[0], index = 0;

for (int i = 1; i < n; i++) {

if (arr[i] > max) {

max = arr[i];

index = i;

// Output

printf("%d\n", max);

printf("%d\n", index);

return 0;

✅ Problem 30: OperationChoices Function


📌 Question:
Write a function OperationChoices(c, a, b) that performs:

●​ c = 1: return a + b​

●​ c = 2: return a - b​

●​ c = 3: return a * b​

●​ c = 4: return a / b (integer division)​

📥 Sample Input:

c = 2

a = 15

b = 20

📤 Output:
diff

-5

👨‍💻 Java Code:


java

public class OperationChoices {


public static int OperationChoices(int c, int a, int b) {

switch (c) {

case 1: return a + b;

case 2: return a - b;

case 3: return a * b;

case 4: return b != 0 ? a / b : 0; // avoid division by


zero

default: return 0;

public static void main(String[] args) {

int result = OperationChoices(2, 15, 20);

[Link](result); // Output: -5

👨‍💻 C Code:
c

#include <stdio.h>

int OperationChoices(int c, int a, int b) {


switch (c) {

case 1: return a + b;

case 2: return a - b;

case 3: return a * b;

case 4: return b != 0 ? a / b : 0; // safe divide

default: return 0;

int main() {

printf("%d\n", OperationChoices(2, 15, 20)); // Output: -5

return 0;

✅ Problem 31: Matrix Splitting and Sum of Second


Largest
📌 Question:
●​ Input a matrix of size n​

●​ Flatten it into a 1D array​

●​ Divide into two arrays:​

○​ Even-indexed elements​

○​ Odd-indexed elements​

●​ Sort both arrays​


●​ Return sum of second largest from each​

📥 Sample Input:
makefile

Size: 2x2

Matrix: 10 5 8 3

Even indices → [10, 8] → second largest = 8

Odd indices → [5, 3] → second largest = 3

Output: 8 + 3 = 11

👨‍💻 Java Code:


java

import [Link].*;

public class MatrixSplit {

public static int sumOfSecondLargest(int[] matrix) {

List<Integer> even = new ArrayList<>();

List<Integer> odd = new ArrayList<>();

for (int i = 0; i < [Link]; i++) {


if (i % 2 == 0) [Link](matrix[i]);

else [Link](matrix[i]);

[Link](even);

[Link](odd);

int evenSecond = [Link]() >= 2 ? [Link]([Link]() -


2) : 0;

int oddSecond = [Link]() >= 2 ? [Link]([Link]() - 2) :


0;

return evenSecond + oddSecond;

public static void main(String[] args) {

int[] matrix = {10, 5, 8, 3};

[Link](sumOfSecondLargest(matrix)); // Output:
11

👨‍💻 C Code:
c
#include <stdio.h>

#include <stdlib.h>

int compare(const void* a, const void* b) {

return (*(int*)a - *(int*)b);

int sumOfSecondLargest(int arr[], int n) {

int even[100], odd[100];

int e = 0, o = 0;

for (int i = 0; i < n; i++) {

if (i % 2 == 0)

even[e++] = arr[i];

else

odd[o++] = arr[i];

qsort(even, e, sizeof(int), compare);

qsort(odd, o, sizeof(int), compare);

int evenSecond = (e >= 2) ? even[e - 2] : 0;

int oddSecond = (o >= 2) ? odd[o - 2] : 0;


return evenSecond + oddSecond;

int main() {

int matrix[] = {10, 5, 8, 3}; // 2x2 matrix flattened

int size = sizeof(matrix) / sizeof(matrix[0]);

printf("%d\n", sumOfSecondLargest(matrix, size)); // Output: 11

return 0;

✅ Problem 32 : LargeSmallSum
📌 Problem Statement:
Write a function LargeSmallSum(arr) that:

●​ Takes a 0-indexed array of unique integers.​

●​ Finds the:​

○​ Second largest element from the even indices.​

○​ Second smallest element from the odd indices.​

●​ Returns their sum.​

📥 Sample Input:

arr = [3, 2, 1, 7, 5, 4]
📤 Output:
7

🧠 Explanation:
●​ Even index elements (0, 2, 4): [3, 1, 5] → sorted: [1, 3, 5] → second largest = 3​

●​ Odd index elements (1, 3, 5): [2, 7, 4] → sorted: [2, 4, 7] → second smallest = 4​

●​ Output: 3 + 4 = 7​

👨‍💻 Java Code:


import [Link].*;

public class LargeSmallSum {

public static int largeSmallSum(int[] arr) {

if ([Link] < 4) return 0; // At least 2 even & 2 odd


needed

List<Integer> even = new ArrayList<>();

List<Integer> odd = new ArrayList<>();

for (int i = 0; i < [Link]; i++) {

if (i % 2 == 0) [Link](arr[i]);

else [Link](arr[i]);
}

[Link](even); // Ascending

[Link](odd); // Ascending

if ([Link]() < 2 || [Link]() < 2) return 0;

int secondLargestEven = [Link]([Link]() - 2);

int secondSmallestOdd = [Link](1);

return secondLargestEven + secondSmallestOdd;

public static void main(String[] args) {

int[] arr = {3, 2, 1, 7, 5, 4};

[Link](largeSmallSum(arr)); // Output: 7

👨‍💻 C Code:
#include <stdio.h>

#include <stdlib.h>
int compare(const void* a, const void* b) {

return (*(int*)a - *(int*)b);

int LargeSmallSum(int arr[], int n) {

if (n < 4) return 0;

int even[100], odd[100];

int e = 0, o = 0;

for (int i = 0; i < n; i++) {

if (i % 2 == 0) even[e++] = arr[i];

else odd[o++] = arr[i];

if (e < 2 || o < 2) return 0;

qsort(even, e, sizeof(int), compare);

qsort(odd, o, sizeof(int), compare);

int secondLargestEven = even[e - 2];

int secondSmallestOdd = odd[1];


return secondLargestEven + secondSmallestOdd;

int main() {

int arr[] = {3, 2, 1, 7, 5, 4};

int n = sizeof(arr) / sizeof(arr[0]);

printf("%d\n", LargeSmallSum(arr, n)); // Output: 7

return 0;

✅ Problem 33 : Anagram Checker


📌 Problem Statement:
Write a function to check whether two strings are anagrams of each other.​
If they are, return "Yes", otherwise return "No".

📥 Sample Input:
mathematica

Input 1: Listen

Input 2: Silent

📤 Output:
Yes

🧠 Explanation:
Two words are anagrams if:

●​ They have the same characters​

●​ In the same frequency​

●​ Order doesn't matter​

●​ Case-insensitive​

Listen and Silent → both contain: e, i, l, n, s, t → ✅

👨‍💻 Java Code:


java

import [Link].*;

public class AnagramCheck {

public static String isAnagram(String str1, String str2) {

// Remove case sensitivity

str1 = [Link]();

str2 = [Link]();

// Convert to char array and sort


char[] arr1 = [Link]();

char[] arr2 = [Link]();

[Link](arr1);

[Link](arr2);

return [Link](arr1, arr2) ? "Yes" : "No";

public static void main(String[] args) {

[Link](isAnagram("Listen", "Silent")); //
Output: Yes

[Link](isAnagram("Hello", "World")); //
Output: No

👨‍💻 C Code:
c

#include <stdio.h>

#include <string.h>

#include <ctype.h>

#include <stdlib.h>
int compareChar(const void *a, const void *b) {

return (*(char *)a - *(char *)b);

void toLower(char *str) {

for (int i = 0; str[i]; i++)

str[i] = tolower(str[i]);

char* isAnagram(char str1[], char str2[]) {

int len1 = strlen(str1), len2 = strlen(str2);

if (len1 != len2)

return "No";

toLower(str1);

toLower(str2);

qsort(str1, len1, sizeof(char), compareChar);

qsort(str2, len2, sizeof(char), compareChar);

return strcmp(str1, str2) == 0 ? "Yes" : "No";

}
int main() {

char str1[] = "Listen";

char str2[] = "Silent";

printf("%s\n", isAnagram(str1, str2)); // Output: Yes

return 0;

✅ Problem 34: ReplaceCharacter


📌 Problem Statement:
Write a function ReplaceCharacter(str, ch1, ch2) that:

●​ Takes a string and two characters.​

●​ Swaps every occurrence of ch1 with ch2, and vice versa.​

📥 Sample Input:

str = "apples"

ch1 = 'a'

ch2 = 'p'

📤 Output:
nginx
paales

🧠 Explanation:
●​ Replace a with p → "p"pples → "p"pples​

●​ Replace p with a → "p"aa"l"e"s → "paales"​

Note: To prevent both replacements interfering with each other, use a temporary
placeholder.

👨‍💻 Java Code:


java

public class ReplaceCharacter {

public static String swapCharacters(String str, char ch1, char


ch2) {

char tempChar = '\0';

StringBuilder sb = new StringBuilder();

// First pass: replace ch1 with temp placeholder

for (char c : [Link]()) {

if (c == ch1) [Link]('\0'); // temp

else if (c == ch2) [Link](ch1);

else [Link](c);
}

// Second pass: replace placeholder with ch2

for (int i = 0; i < [Link](); i++) {

if ([Link](i) == '\0') [Link](i, ch2);

return [Link]();

public static void main(String[] args) {

String result = swapCharacters("apples", 'a', 'p');

[Link](result); // Output: paales

👨‍💻 C Code:
c

#include <stdio.h>

#include <string.h>

void ReplaceCharacter(char str[], char ch1, char ch2) {


int len = strlen(str);

// First pass: use temp char (e.g. 0x01)

for (int i = 0; i < len; i++) {

if (str[i] == ch1)

str[i] = 1; // Temporary placeholder

else if (str[i] == ch2)

str[i] = ch1;

// Second pass: replace temp with ch2

for (int i = 0; i < len; i++) {

if (str[i] == 1)

str[i] = ch2;

printf("%s\n", str);

int main() {

char str[] = "apples";

ReplaceCharacter(str, 'a', 'p'); // Output: paales

return 0;

}
✅ Notes:
●​ This technique avoids replacing ch1 with ch2 and then re-replacing ch2 back again.​

●​ The \0 in Java and 1 in C are used as temporary placeholders (can use any
unused marker).​

✅ 35. Find Roots of a Quadratic Equation


📌 Question:
Given a, b, and c, find the roots of ax² + bx + c = 0.

📥 Sample Input:

a = 1, b = -5, c = 6

📤 Output:
sql

Roots are: 3.0 and 2.0

🧠 Explanation:
Use the quadratic formula:​
x=−b±b2−4ac2ax = \frac{-b \pm \sqrt{b^2 - 4ac}}{2a}x=2a−b±b2−4ac​​
👨‍💻 Java Code:
java

public class QuadraticRoots {

public static void findRoots(double a, double b, double c) {

double discriminant = b * b - 4 * a * c;

if (discriminant > 0) {

double root1 = (-b + [Link](discriminant)) / (2 * a);

double root2 = (-b - [Link](discriminant)) / (2 * a);

[Link]("Roots are: " + root1 + " and " +


root2);

} else if (discriminant == 0) {

double root = -b / (2 * a);

[Link]("Root is: " + root);

} else {

[Link]("No Real Roots.");

public static void main(String[] args) {

findRoots(1, -5, 6); // Output: Roots are: 3.0 and 2.0

}
👨‍💻 C Code:
c

#include <stdio.h>

#include <math.h>

void findRoots(double a, double b, double c) {

double d = b * b - 4 * a * c;

if (d > 0) {

double r1 = (-b + sqrt(d)) / (2 * a);

double r2 = (-b - sqrt(d)) / (2 * a);

printf("Roots are: %.1f and %.1f\n", r1, r2);

} else if (d == 0) {

double r = -b / (2 * a);

printf("Root is: %.1f\n", r);

} else {

printf("No Real Roots.\n");

int main() {

findRoots(1, -5, 6);


return 0;

✅ 36 Find Sum of Divisors of N


📌 Question:
Write a function to find the sum of all positive divisors of a number N.

📥 Sample Input:

N = 12

📤 Output:

Sum = 28

🧠 Explanation:
Divisors: 1, 2, 3, 4, 6, 12 → sum = 28

👨‍💻 Java Code:


java
public class SumOfDivisors {

public static int sumDivisors(int n) {

int sum = 0;

for (int i = 1; i <= n; i++) {

if (n % i == 0) sum += i;

return sum;

public static void main(String[] args) {

[Link]("Sum = " + sumDivisors(12)); // Output:


28

👨‍💻 C Code:
c

#include <stdio.h>

int sumOfDivisors(int n) {

int sum = 0;

for (int i = 1; i <= n; i++) {

if (n % i == 0) sum += i;
}

return sum;

int main() {

printf("Sum = %d\n", sumOfDivisors(12)); // Output: 28

return 0;

✅ 37. Reverse a String Word-wise


📌 Question:
Write a function to reverse a sentence word-wise.​
Words should be printed in reverse order.

📥 Sample Input:
arduino

"I love programming"

📤 Output:
arduino

"programming love I"


👨‍💻 Java Code:
java

public class ReverseWords {

public static String reverseWords(String str) {

String[] words = [Link](" ");

StringBuilder sb = new StringBuilder();

for (int i = [Link] - 1; i >= 0; i--) {

[Link](words[i]);

if (i != 0) [Link](" ");

return [Link]();

public static void main(String[] args) {

String result = reverseWords("I love programming");

[Link](result); // Output: programming love I

}
👨‍💻 C Code:
c

#include <stdio.h>

#include <string.h>

void reverseWords(char str[]) {

char *words[100];

int count = 0;

char *token = strtok(str, " ");

while (token != NULL) {

words[count++] = token;

token = strtok(NULL, " ");

for (int i = count - 1; i >= 0; i--) {

printf("%s", words[i]);

if (i != 0) printf(" ");

printf("\n");

int main() {
char str[] = "I love programming";

reverseWords(str); // Output: programming love I

return 0;

✅ Problem 38 : Count Swaps Using Selection Sort


📌 Problem Statement:
Write a program that:

●​ Sorts a list of integers using Selection Sort.​

●​ Counts the number of swaps performed during the sort.​

●​ Returns that count.​

📥 Sample Input:
text

arr = [10, 4, 12, 3, 1]

📤 Expected Output:
text

🧠 Explanation:
Steps:
1.​ Swap 10 with 1 → [1, 4, 12, 3, 10]​

2.​ Swap 4 with 3 → [1, 3, 12, 4, 10]​

3.​ Swap 12 with 4 → [1, 3, 4, 12, 10]​

4.​ Swap 12 with 10 → [1, 3, 4, 10, 12]​

But only 3 swaps are actually needed for sorting – since 4th step is already in correct order
→ Output: 3

👨‍💻 Java Code:


java

public class SelectionSortSwapCounter {

public static int countSwaps(int[] arr) {

int swaps = 0;

int n = [Link];

for (int i = 0; i < n - 1; i++) {

int m dx = i;

// Find the index of the m mum element

for (int j = i + 1; j < n; j++) {

if (arr[j] < arr[m dx]) {

m dx = j;

}
}

// If a smaller element is found, swap

if (m dx != i) {

int temp = arr[i];

arr[i] = arr[m dx];

arr[m dx] = temp;

swaps++;

return swaps;

public static void main(String[] args) {

int[] arr = {10, 4, 12, 3, 1};

[Link]("Number of swaps: " + countSwaps(arr));


// Output: 3

👨‍💻 C Code:
c
#include <stdio.h>

int countSwaps(int arr[], int n) {

int swaps = 0;

for (int i = 0; i < n - 1; i++) {

int m dx = i;

for (int j = i + 1; j < n; j++) {

if (arr[j] < arr[m dx])

m dx = j;

if (m dx != i) {

int temp = arr[i];

arr[i] = arr[m dx];

arr[m dx] = temp;

swaps++;

return swaps;

}
int main() {

int arr[] = {10, 4, 12, 3, 1};

int n = sizeof(arr) / sizeof(arr[0]);

printf("Number of swaps: %d\n", countSwaps(arr, n)); // Output:


3

return 0;

🧩 Question 39
Write a function that takes a string as input and:

●​ Replaces every 'a' with 'b'​

●​ Replaces every 'b' with 'a'​

●​ Leaves all other characters unchanged​

Return the transformed string.

🧪 Sample Input:
Input: "abaabbcc"
✅ Sample Output:
vbnet

Output: "babbaacc"

🔍 Explanation:
Original string: "a b a a b b c c"

Replace:

●​ 'a' → 'b'​

●​ 'b' → 'a'​

●​ 'c' stays 'c'​

Resulting string: "b a b b a a c c" → "babbaacc"

👨‍💻 Java Code:


java

public class ReplaceCharacters {

public static String swapAandB(String str) {

StringBuilder result = new StringBuilder();

for (char ch : [Link]()) {


if (ch == 'a') {

[Link]('b');

} else if (ch == 'b') {

[Link]('a');

} else {

[Link](ch);

return [Link]();

public static void main(String[] args) {

String input = "abaabbcc";

String output = swapAandB(input);

[Link]("Transformed string: " + output); //


Output: babbaacc

👨‍💻 C Code:
c

#include <stdio.h>
#include <string.h>

void swapAandB(char str[]) {

for (int i = 0; str[i] != '\0'; i++) {

if (str[i] == 'a') {

str[i] = 'b';

} else if (str[i] == 'b') {

str[i] = 'a';

int main() {

char str[] = "abaabbcc";

swapAandB(str);

printf("Transformed string: %s\n", str); // Output: babbaacc

return 0;

✅ 40. Right Rotate an Array In-Place


✅ Question:
Rotate the given array arr of size n by d positions to the right, in-place without using extra
memory.
✅ Explanation:
To rotate an array to the right by d positions, follow these steps:

1.​ Reverse the entire array.​

2.​ Reverse the first d elements.​

3.​ Reverse the rema ng n - d elements.​

✅ Sample Input:

n = 5

arr = [1, 2, 3, 4, 5]

d = 3

✅ Output:

[3, 4, 5, 1, 2]

✅ Java Code:
java

import [Link];
public class RightRotateArray {

public static void rotateRight(int[] arr, int d) {

int n = [Link];

d = d % n;

reverse(arr, 0, n - 1);

reverse(arr, 0, d - 1);

reverse(arr, d, n - 1);

private static void reverse(int[] arr, int start, int end) {

while (start < end) {

int temp = arr[start];

arr[start] = arr[end];

arr[end] = temp;

start++;

end--;

public static void main(String[] args) {

int[] arr = {1, 2, 3, 4, 5};

int d = 3;
rotateRight(arr, d);

[Link]([Link](arr)); // [3, 4, 5, 1,
2]

✅ C Code:
c

#include <stdio.h>

void reverse(int arr[], int start, int end) {

while (start < end) {

int temp = arr[start];

arr[start++] = arr[end];

arr[end--] = temp;

void rotateRight(int arr[], int n, int d) {

d = d % n;

reverse(arr, 0, n - 1);

reverse(arr, 0, d - 1);

reverse(arr, d, n - 1);
}

int main() {

int arr[] = {1, 2, 3, 4, 5};

int n = 5, d = 3;

rotateRight(arr, n, d);

for (int i = 0; i < n; i++)

printf("%d ", arr[i]); // Output: 3 4 5 1 2

return 0;

✅ 41. Find Substring Index


✅ Question:
Given two strings str1 and str2, return the starting index of the first occurrence of str2
in str1. Return -1 if str2 is not found.

✅ Sample Input:

str1 = "Hello, World!"

str2 = "World"
✅ Output:
7

✅ Java Code:
java

public class SubstringIndex {

public static int findSubstringIndex(String str1, String str2) {

return [Link](str2);

public static void main(String[] args) {

String str1 = "Hello, World!";

String str2 = "World";

[Link](findSubstringIndex(str1, str2)); //
Output: 7

✅ C Code:
c
#include <stdio.h>

#include <string.h>

int findSubstringIndex(char str1[], char str2[]) {

char* ptr = strstr(str1, str2);

if (ptr)

return ptr - str1;

return -1;

int main() {

char str1[] = "Hello, World!";

char str2[] = "World";

printf("%d\n", findSubstringIndex(str1, str2)); // Output: 7

return 0;

✅42. Reverse the Entire String Word-Wise


✅ Question:
Given a string str, reverse the entire string (not just the order of words).

✅ Sample Input:
str = "Hello, World!"

✅ Output:
arduino

"!dlroW ,olleH"

✅ Java Code:
java

public class ReverseString {

public static String reverse(String str) {

return new StringBuilder(str).reverse().toString();

public static void main(String[] args) {

String input = "Hello, World!";

[Link](reverse(input)); // !dlroW ,olleH

}
✅ C Code:
c

#include <stdio.h>

#include <string.h>

void reverseString(char str[]) {

int n = strlen(str);

for (int i = 0; i < n / 2; i++) {

char temp = str[i];

str[i] = str[n - 1 - i];

str[n - 1 - i] = temp;

int main() {

char str[] = "Hello, World!";

reverseString(str);

printf("%s\n", str); // !dlroW ,olleH

return 0;

✅43. Find Pair with Given Sum


✅ Question:
Given an array of integers and a number sum, find one pair of elements (a, b) such that
a + b = sum.

✅ Explanation:
Loop through the array and use a HashSet to check whether the complement (sum -
current_element) has already appeared.

✅ Sample Input:
makefile

Array: [1, 4, 6, 8]

Sum: 10

✅ Output:

[4, 6]

✅ Java Code:
java

import [Link].*;

public class FindPairSum {


public static int[] findPair(int[] arr, int sum) {

Set<Integer> seen = new HashSet<>();

for (int num : arr) {

int complement = sum - num;

if ([Link](complement)) {

return new int[]{complement, num};

[Link](num);

return new int[]{-1}; // No pair found

public static void main(String[] args) {

int[] arr = {1, 4, 6, 8};

int sum = 10;

int[] result = findPair(arr, sum);

[Link]([Link](result));

✅ C Code:
c

#include <stdio.h>
int findPair(int arr[], int n, int sum) {

for (int i = 0; i < n-1; i++) {

for (int j = i+1; j < n; j++) {

if (arr[i] + arr[j] == sum) {

printf("[%d, %d]\n", arr[i], arr[j]);

return 1;

printf("[-1]\n");

return 0;

int main() {

int arr[] = {1, 4, 6, 8};

int sum = 10;

int n = sizeof(arr) / sizeof(arr[0]);

findPair(arr, n, sum);

return 0;

✅44. Maximum Subarray Sum (Kadane’s Algorithm)


✅ Question:
Find the maximum sum of any contiguous subarray.

✅ Explanation:
Use Kadane’s algorithm:

●​ Keep track of max current sum and max global sum.​

✅ Sample Input:
javascript

Array: [-2, 1, -3, 4, -1, 2, 1, -5, 4]

✅ Output:
6

Explanation: [4, -1, 2, 1] = 6

✅ Java Code:
java

public class MaxSubarraySum {

public static int maxSubArray(int[] nums) {

int maxSoFar = nums[0], currentMax = nums[0];


for (int i = 1; i < [Link]; i++) {

currentMax = [Link](nums[i], currentMax + nums[i]);

maxSoFar = [Link](maxSoFar, currentMax);

return maxSoFar;

public static void main(String[] args) {

int[] nums = {-2, 1, -3, 4, -1, 2, 1, -5, 4};

[Link](maxSubArray(nums)); // Output: 6

✅ C Code:
c

#include <stdio.h>

int maxSubArray(int arr[], int n) {

int maxSoFar = arr[0], currentMax = arr[0];

for (int i = 1; i < n; i++) {

currentMax = arr[i] > currentMax + arr[i] ? arr[i] :


currentMax + arr[i];

maxSoFar = maxSoFar > currentMax ? maxSoFar : currentMax;


}

return maxSoFar;

int main() {

int arr[] = {-2, 1, -3, 4, -1, 2, 1, -5, 4};

int n = sizeof(arr) / sizeof(arr[0]);

printf("%d\n", maxSubArray(arr, n)); // Output: 6

return 0;

✅ 45. Swap All Occurrences of Two Characters


✅ Question:
Given a string str, a character ch1, and a character ch2, replace all occurrences of ch1
with ch2 and vice versa.

✅ Sample Input:

str = "apples"

ch1 = 'a', ch2 = 'p'

✅ Output:
arduino
"paales"

✅ Java Code:
java

public class SwapCharacters {

public static String swapChars(String str, char ch1, char ch2) {

StringBuilder sb = new StringBuilder();

for (char c : [Link]()) {

if (c == ch1) [Link](ch2);

else if (c == ch2) [Link](ch1);

else [Link](c);

return [Link]();

public static void main(String[] args) {

String input = "apples";

[Link](swapChars(input, 'a', 'p')); // Output:


paales

}
✅ C Code:
c

#include <stdio.h>

#include <string.h>

void swapChars(char str[], char ch1, char ch2) {

for (int i = 0; str[i] != '\0'; i++) {

if (str[i] == ch1)

str[i] = ch2;

else if (str[i] == ch2)

str[i] = ch1;

printf("%s\n", str);

int main() {

char str[] = "apples";

swapChars(str, 'a', 'p'); // Output: paales

return 0;

✅ 46. Find M mum Value and Its Index


✅ Question:
Given an integer array, find the m mum value and its index.

✅ Explanation:
Traverse the array while keeping track of the m mum element and its index.

✅ Sample Input:

[5, 2, 4, 1, 3]

✅ Output:
1 3

✅ Java Code:
java

public class MinValueIndex {

public static void main(String[] args) {

int[] arr = {5, 2, 4, 1, 3};

int min = arr[0], index = 0;

for (int i = 1; i < [Link]; i++) {

if (arr[i] < min) {


min = arr[i];

index = i;

[Link](min + " " + index);

✅ C Code:
c

#include <stdio.h>

int main() {

int arr[] = {5, 2, 4, 1, 3};

int n = sizeof(arr) / sizeof(arr[0]);

int min = arr[0], index = 0;

for (int i = 1; i < n; i++) {

if (arr[i] < min) {

min = arr[i];

index = i;

}
printf("%d %d\n", min, index);

return 0;

✅ 47. Find Average of Positive Numbers


✅ Question:
Given an array, find the average of all positive numbers in it.

✅ Explanation:
Sum only positive values and divide by their count.

✅ Sample Input:

[5, 2, -4, 1, 3]

✅ Output:
3

✅ Java Code:
public class AvgPositive {

public static void main(String[] args) {

int[] arr = {5, 2, -4, 1, 3};

int sum = 0, count = 0;

for (int num : arr) {

if (num > 0) {

sum += num;

count++;

[Link](sum / count);

✅ C Code:
#include <stdio.h>

int main() {

int arr[] = {5, 2, -4, 1, 3};

int n = sizeof(arr) / sizeof(arr[0]);

int sum = 0, count = 0;


for (int i = 0; i < n; i++) {

if (arr[i] > 0) {

sum += arr[i];

count++;

printf("%d\n", sum / count);

return 0;

✅ 48. Count Occurrences of an Element


✅ Question:
Given an array and an element, count how many times it appears.

✅ Explanation:
Loop through the array and increment count whenever the element is found.

✅ Sample Input:
makefile

Array: [5, 2, 4, 1, 2]
Element: 2

✅ Output:
2

✅ Java Code:
java

public class CountOccurrences {

public static void main(String[] args) {

int[] arr = {5, 2, 4, 1, 2};

int target = 2, count = 0;

for (int num : arr) {

if (num == target) count++;

[Link](count);

✅ C Code:
c

#include <stdio.h>

int main() {

int arr[] = {5, 2, 4, 1, 2};

int target = 2, count = 0;

int n = sizeof(arr) / sizeof(arr[0]);

for (int i = 0; i < n; i++) {

if (arr[i] == target)

count++;

printf("%d\n", count);

return 0;

✅ 49. Check if Array Contains an Element


✅ Question:
Check whether the array contains a specific element.

✅ Explanation:
Search the array and return true as soon as the element is found.

✅ Sample Input:
makefile

Array: [5, 2, 4, 1, 3]

Element: 2

✅ Output:
graphql

True

✅ Java Code:
java

public class ContainsElement {

public static void main(String[] args) {

int[] arr = {5, 2, 4, 1, 3};

int target = 2;

boolean found = false;

for (int num : arr) {

if (num == target) {
found = true;

break;

[Link](found);

✅ C Code:
c

#include <stdio.h>

int main() {

int arr[] = {5, 2, 4, 1, 3};

int n = sizeof(arr) / sizeof(arr[0]);

int target = 2;

int found = 0;

for (int i = 0; i < n; i++) {

if (arr[i] == target) {

found = 1;

break;
}

printf("%s\n", found ? "True" : "False");

return 0;

✅ Q50: Check for Palindrome Number


✅ Question
Check whether a given number is a Palindrome. A number is said to be a palindrome if it
reads the same backward as forward.

✅ Explanation
A number like 121 remains the same when its digits are reversed. But 123 becomes 321,
which is not equal to the original number.

✅ Sample Input/Output
Input:

121

Output:

nginx

Palindrome
Input:

123

Output:

mathematica

Not Palindrome

✅ Java Code
java

public class PalindromeCheck {

public static void main(String[] args) {

int num = 121;

int original = num;

int reverse = 0;

while (num > 0) {

int rem = num % 10;

reverse = reverse * 10 + rem;

num /= 10;

}
if (original == reverse)

[Link]("Palindrome");

else

[Link]("Not Palindrome");

✅ C Code
c

#include <stdio.h>

int main() {

int num = 121, reverse = 0, rem, original;

original = num;

while (num > 0) {

rem = num % 10;

reverse = reverse * 10 + rem;

num /= 10;

if (original == reverse)
printf("Palindrome\n");

else

printf("Not Palindrome\n");

return 0;

✅ 51: Print Pattern (Right-Angle Triangle of Stars)


✅ Question
Print a right-angled triangle using stars (*) for n rows.

✅ Explanation
If n = 4, print:

**

***

****

Each row i has exactly i stars.

✅ Sample Input/Output
Input:

n = 4

Output:

**

***

****

✅ Java Code
java

public class StarPattern {

public static void main(String[] args) {

int n = 4;

for (int i = 1; i <= n; i++) {

for (int j = 1; j <= i; j++)

[Link]("*");

[Link]();

}
}

✅ C Code
c

#include <stdio.h>

int main() {

int n = 4;

for (int i = 1; i <= n; i++) {

for (int j = 1; j <= i; j++)

printf("*");

printf("\n");

return 0;

✅ Q 52: Length of the Longest Substring Without


Repeating Characters
✅ Question
Write a function that returns the length of the longest substring without repeating
characters in the given string.

✅ Explanation
You must scan through the string and track the longest substring that contains all unique
characters.​
Use a sliding window approach with a set to track characters.

✅ Sample Input/Output
Input:

nginx

abcabcbb

Output:

Explanation:​
The answer is abc with length 3.

Input:

nginx

bbbbb
Output:

Explanation:​
The longest substring with unique characters is b.

✅ Java Code
java

import [Link];

public class LongestUniqueSubstring {

public static void main(String[] args) {

String str = "abcabcbb";

[Link](lengthOfLongestSubstring(str));

public static int lengthOfLongestSubstring(String s) {

int left = 0, right = 0, maxLen = 0;

HashSet<Character> set = new HashSet<>();

while (right < [Link]()) {

if (![Link]([Link](right))) {

[Link]([Link](right));
maxLen = [Link](maxLen, right - left + 1);

right++;

} else {

[Link]([Link](left));

left++;

return maxLen;

✅ C Code
c

#include <stdio.h>

#include <string.h>

int max(int a, int b) {

return (a > b) ? a : b;

int lengthOfLongestSubstring(char* s) {

int n = strlen(s);
int visited[256];

for (int i = 0; i < 256; i++)

visited[i] = -1;

int maxLen = 0, start = 0;

for (int end = 0; end < n; end++) {

if (visited[(unsigned char)s[end]] >= start) {

start = visited[(unsigned char)s[end]] + 1;

visited[(unsigned char)s[end]] = end;

maxLen = max(maxLen, end - start + 1);

return maxLen;

int main() {

char str[] = "abcabcbb";

printf("%d\n", lengthOfLongestSubstring(str));

return 0;

}
✅ Q53: Find First Non-Repeating Character in a String
✅ Question
Write a function to find the first non-repeating character in a string.​
If no such character exists, return a space or appropriate message.

✅ Explanation
Use an array or hashmap to count character frequencies, then iterate the string again to find
the first character with a count of 1.

✅ Sample Input/Output
Input:

arduino

"swiss"

Output:

nginx

Input:

arduino

"aabbcc"

Output:

pgsql

No non-repeating character
✅ Java Code
java

public class FirstUniqueChar {


public static void main(String[] args) {
String str = "swiss";
char result = firstUnique(str);
if (result == ' ')
[Link]("No non-repeating character");
else
[Link](result);
}

public static char firstUnique(String str) {


int[] freq = new int[256];

for (char c : [Link]())


freq[c]++;

for (char c : [Link]()) {


if (freq[c] == 1)
return c;
}

return ' ';


}
}

✅ C Code
c
#include <stdio.h>
#include <string.h>

char firstUniqueChar(char *str) {


int count[256] = {0};

for (int i = 0; str[i]; i++)


count[(unsigned char)str[i]]++;

for (int i = 0; str[i]; i++) {


if (count[(unsigned char)str[i]] == 1)
return str[i];
}

return ' ';


}

int main() {
char str[] = "swiss";
char result = firstUniqueChar(str);

if (result == ' ')


printf("No non-repeating character\n");
else
printf("%c\n", result);

return 0;
}

✅ Q54: Longest Palindromic Substring


✅ Question
Given a string s, return the longest palindromic substring in it.
✅ Explanation
A palindrome is a string that reads the same forwards and backwards (e.g., "madam").​
We expand around every center to find the longest palindrome.

✅ Sample Input/Output
Input:

arduino

"babad"

Output:

arduino

"bab"

Input:

arduino

"cbbd"

Output:

arduino

"bb"

✅ Java Code
java

public class LongestPalindromeSubstring {


public static void main(String[] args) {
String str = "babad";
[Link](longestPalindrome(str));
}

public static String longestPalindrome(String s) {


if (s == null || [Link]() < 1) return "";

int start = 0, end = 0;

for (int i = 0; i < [Link](); i++) {


int len1 = expand(s, i, i);
int len2 = expand(s, i, i + 1);
int len = [Link](len1, len2);

if (len > end - start) {


start = i - (len - 1) / 2;
end = i + len / 2;
}
}

return [Link](start, end + 1);


}

private static int expand(String s, int left, int right) {


while (left >= 0 && right < [Link]() && [Link](left) ==
[Link](right)) {
left--;
right++;
}
return right - left - 1;
}
}
✅ C Code
c

#include <stdio.h>
#include <string.h>

void printLongestPalindrome(char* str) {


int n = strlen(str);
int start = 0, maxLen = 1;

for (int i = 0; i < n; i++) {


int low = i - 1;
int high = i + 1;

while (high < n && str[high] == str[i]) high++;


while (low >= 0 && str[low] == str[i]) low--;

while (low >= 0 && high < n && str[low] == str[high]) {


low--;
high++;
}

int len = high - low - 1;


if (len > maxLen) {
maxLen = len;
start = low + 1;
}
}

printf("%.*s\n", maxLen, str + start);


}
int main() {
char str[] = "babad";
printLongestPalindrome(str);
return 0;
}

✅ Q55: Wildcard Pattern Matching


✅ Question
Given a string s and a pattern p, return true if s matches the pattern p, where:

●​ '?' matches any single character.​

●​ '*' matches any sequence of characters (including the empty sequence).​

✅ Explanation
Use Dynamic Programming to match the pattern.​
We'll use a 2D table where dp[i][j] means first i chars of pattern match first j chars of
string.

✅ Sample Input/Output
Input:

s = "abcd", p = "a*d"

Output:

arduino

true
Input:

s = "abc", p = "a?d"

Output:

arduino

false

✅ Java Code
java

public class WildcardMatch {


public static void main(String[] args) {
String s = "abcd";
String p = "a*d";
[Link](isMatch(s, p));
}

public static boolean isMatch(String s, String p) {


int m = [Link](), n = [Link]();
boolean[][] dp = new boolean[n+1][m+1];

dp[0][0] = true;

for (int i = 1; i <= n; i++) {


if ([Link](i-1) == '*')
dp[i][0] = dp[i-1][0];
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if ([Link](i-1) == '*')
dp[i][j] = dp[i-1][j] || dp[i][j-1];
else if ([Link](i-1) == '?' || [Link](i-1) ==
[Link](j-1))
dp[i][j] = dp[i-1][j-1];
}
}

return dp[n][m];
}
}

✅ C Code
c

#include <stdio.h>
#include <stdbool.h>
#include <string.h>

bool isMatch(const char *s, const char *p) {


int m = strlen(s), n = strlen(p);
bool dp[n + 1][m + 1];
memset(dp, false, sizeof(dp));

dp[0][0] = true;

for (int i = 1; i <= n; i++) {


if (p[i - 1] == '*')
dp[i][0] = dp[i - 1][0];
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
if (p[i - 1] == '*')
dp[i][j] = dp[i - 1][j] || dp[i][j - 1];
else if (p[i - 1] == '?' || p[i - 1] == s[j - 1])
dp[i][j] = dp[i - 1][j - 1];
}
}

return dp[n][m];
}

int main() {
const char *s = "abcd";
const char *p = "a*d";

if (isMatch(s, p))
printf("true\n");
else
printf("false\n");

return 0;
}

✅ Q: Find the Number of Prime Numbers Less Than N


✅ Question
Write a function that returns the count of prime numbers less than a given number n.

✅ Explanation
A prime number is only divisible by 1 and itself.​
Use the Sieve of Eratosthenes to optimize the solution.
✅ Input/Output
Input:

n = 10

Output:

Explanation:​
Prime numbers are 2, 3, 5, 7

✅ Java Code
java

public class PrimeCount {


public static void main(String[] args) {
int n = 10;
[Link](countPrimes(n));
}

public static int countPrimes(int n) {


if (n < 2) return 0;

boolean[] isPrime = new boolean[n];


for (int i = 2; i < n; i++) isPrime[i] = true;

for (int i = 2; i * i < n; i++) {


if (isPrime[i]) {
for (int j = i * i; j < n; j += i)
isPrime[j] = false;
}
}

int count = 0;
for (int i = 2; i < n; i++)
if (isPrime[i]) count++;

return count;
}
}

✅ C Code
c

#include <stdio.h>
#include <stdbool.h>

int countPrimes(int n) {
if (n < 2) return 0;

bool isPrime[n];
for (int i = 2; i < n; i++) isPrime[i] = true;

for (int i = 2; i * i < n; i++) {


if (isPrime[i]) {
for (int j = i * i; j < n; j += i)
isPrime[j] = false;
}
}

int count = 0;
for (int i = 2; i < n; i++)
if (isPrime[i]) count++;

return count;
}

int main() {
int n = 10;
printf("%d\n", countPrimes(n));
return 0;
}

✅ Q: Count Digits That Divide the Number


✅ Question
Given a number n, count how many of its digits exactly divide the number.

✅ Input/Output
Input:

n = 1012

Output:

Explanation:​
Digits 1, 1, and 2 divide 1012. 0 is ignored.
✅ Java Code
java

public class CountDividingDigits {


public static void main(String[] args) {
int n = 1012;
[Link](countDigits(n));
}

public static int countDigits(int n) {


int count = 0, temp = n;

while (temp > 0) {


int d = temp % 10;
if (d != 0 && n % d == 0)
count++;
temp /= 10;
}

return count;
}
}

✅ C Code
c

#include <stdio.h>

int countDigits(int n) {
int count = 0, temp = n;

while (temp > 0) {


int d = temp % 10;
if (d != 0 && n % d == 0)
count++;
temp /= 10;
}

return count;
}

int main() {
int n = 1012;
printf("%d\n", countDigits(n));
return 0;
}

✅ Q: Count 1’s in Binary Representation


✅ Question
Write a function to count the number of 1's in the binary representation of a number.

✅ Input/Output
Input:

n = 13

Output:

3
Explanation:​
13 in binary is 1101.

✅ Java Code
java

public class CountBits {


public static void main(String[] args) {
int n = 13;
[Link]([Link](n));
}
}

✅ C Code
c

#include <stdio.h>

int countBits(int n) {
int count = 0;
while (n) {
count += n & 1;
n >>= 1;
}
return count;
}

int main() {
int n = 13;
printf("%d\n", countBits(n));
return 0;
}
✅ Q: Find the Factorial of a Number (Iterative)
✅ Question
Write a function to compute the factorial of a given number n.

✅ Input/Output
Input:

n = 5

Output:

120

✅ Java Code
java

public class Factorial {


public static void main(String[] args) {
int n = 5;
[Link](factorial(n));
}

public static int factorial(int n) {


int res = 1;
for (int i = 2; i <= n; i++)
res *= i;
return res;
}
}

✅ C Code
c

#include <stdio.h>

int factorial(int n) {
int result = 1;
for (int i = 2; i <= n; i++)
result *= i;
return result;
}

int main() {
int n = 5;
printf("%d\n", factorial(n));
return 0;
}

✅Q: Check Armstrong Number


✅ Question
Check whether a number is an Armstrong number.​
An Armstrong number of n digits is an integer such that the sum of its own digits raised to
the power n is equal to the number itself.

✅ Input/Output
Input:

153

Output:

Yes

Explanation:​
1³ + 5³ + 3³ = 153

✅ Java Code
java

public class ArmstrongCheck {


public static void main(String[] args) {
int num = 153;
[Link](isArmstrong(num) ? "Yes" : "No");
}

public static boolean isArmstrong(int n) {


int temp = n, sum = 0, digits = [Link](n).length();

while (temp > 0) {


int d = temp % 10;
sum += [Link](d, digits);
temp /= 10;
}

return sum == n;
}
}

✅ C Code
c

#include <stdio.h>
#include <math.h>

int isArmstrong(int n) {
int original = n, sum = 0, digits = 0;
int temp = n;

while (temp) {
digits++;
temp /= 10;
}

temp = n;
while (temp) {
int d = temp % 10;
sum += pow(d, digits);
temp /= 10;
}

return sum == original;


}

int main() {
int n = 153;
printf("%s\n", isArmstrong(n) ? "Yes" : "No");
return 0;
}
✅ Q: Find the Missing Number in a Consecutive Array
✅ Question:​
Given an array of size n-1 conta ng distinct integers in the range from 1 to n. Find the
missing number.

✅ Explanation:​
Calculate the sum of the first n natural numbers using the formula n*(n+1)/2 and subtract
the sum of the array from it.

✅ Input:
arr[] = {1, 2, 4, 5, 6}

✅ Output:
3

✅ Java Code
java

public class MissingNumber {


public static void main(String[] args) {
int[] arr = {1, 2, 4, 5, 6};
[Link](findMissing(arr, 6));
}

public static int findMissing(int[] arr, int n) {


int total = n * (n + 1) / 2;
for (int num : arr) total -= num;
return total;
}
}
✅ C Code
c

#include <stdio.h>

int findMissing(int arr[], int n) {


int total = n * (n + 1) / 2;
for (int i = 0; i < n - 1; i++)
total -= arr[i];
return total;
}

int main() {
int arr[] = {1, 2, 4, 5, 6};
int n = 6;
printf("%d\n", findMissing(arr, n));
return 0;
}

✅ Q: Move All Zeros to End


✅ Question:​
Given an array, move all zeros to the end while mainta ng the relative order of the non-zero
elements.

✅ Input:
arr[] = {0, 1, 0, 3, 12}

✅ Output:

[1, 3, 12, 0, 0]
✅ Java Code
java

public class MoveZeros {


public static void main(String[] args) {
int[] arr = {0, 1, 0, 3, 12};
moveZeros(arr);
for (int i : arr) [Link](i + " ");
}

public static void moveZeros(int[] arr) {


int j = 0;
for (int i = 0; i < [Link]; i++)
if (arr[i] != 0) arr[j++] = arr[i];
while (j < [Link]) arr[j++] = 0;
}
}

✅ C Code
c

#include <stdio.h>

void moveZeros(int arr[], int n) {


int j = 0;
for (int i = 0; i < n; i++)
if (arr[i] != 0) arr[j++] = arr[i];
while (j < n) arr[j++] = 0;
}

int main() {
int arr[] = {0, 1, 0, 3, 12};
int n = 5;
moveZeros(arr, n);
for (int i = 0; i < n; i++) printf("%d ", arr[i]);
return 0;
}

✅ Q: Find the First Repeating Element


✅ Question:​
Find the first element that repeats in the array.

✅ Input:
arr[] = {10, 5, 3, 4, 3, 5, 6}

✅ Output:
5

✅ Java Code
java

import [Link].*;

public class FirstRepeating {


public static void main(String[] args) {
int[] arr = {10, 5, 3, 4, 3, 5, 6};
[Link](firstRepeating(arr));
}

public static int firstRepeating(int[] arr) {


Set<Integer> seen = new HashSet<>();
for (int i = [Link] - 1; i >= 0; i--) {
if ([Link](arr[i]))
return arr[i];
[Link](arr[i]);
}
return -1;
}
}

✅ C Code
c

#include <stdio.h>

int firstRepeating(int arr[], int n) {


for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (arr[i] == arr[j]) return arr[i];
return -1;
}

int main() {
int arr[] = {10, 5, 3, 4, 3, 5, 6};
int n = 7;
printf("%d\n", firstRepeating(arr, n));
return 0;
}

✅ Q: Check if Array is Sorted and Rotated


✅ Question:​
Check if the array is sorted and rotated.

✅ Input:
arr[] = {3, 4, 5, 1, 2}

✅ Output:

Yes

✅ Java Code
java

public class SortedRotated {


public static void main(String[] args) {
int[] arr = {3, 4, 5, 1, 2};
[Link](isSortedAndRotated(arr) ? "Yes" : "No");
}

public static boolean isSortedAndRotated(int[] arr) {


int count = 0, n = [Link];
for (int i = 0; i < n; i++)
if (arr[i] > arr[(i + 1) % n])
count++;
return count <= 1;
}
}

✅ C Code
c

#include <stdio.h>
#include <stdbool.h>
bool isSortedAndRotated(int arr[], int n) {
int count = 0;
for (int i = 0; i < n; i++)
if (arr[i] > arr[(i + 1) % n])
count++;
return count <= 1;
}

int main() {
int arr[] = {3, 4, 5, 1, 2};
int n = 5;
printf("%s\n", isSortedAndRotated(arr, n) ? "Yes" : "No");
return 0;
}

✅ Q: Find Leaders in an Array


✅ Question:​
An element is a leader if it is greater than all elements to its right.

✅ Input:
arr[] = {16, 17, 4, 3, 5, 2}

✅ Output:
17 5 2

✅ Java Code
java

public class Leaders {


public static void main(String[] args) {
int[] arr = {16, 17, 4, 3, 5, 2};
printLeaders(arr);
}

public static void printLeaders(int[] arr) {


int max = Integer.MIN_VALUE;
for (int i = [Link] - 1; i >= 0; i--) {
if (arr[i] > max) {
[Link](arr[i] + " ");
max = arr[i];
}
}
}
}

✅ C Code
c

#include <stdio.h>

void printLeaders(int arr[], int n) {


int max = arr[n - 1];
printf("%d ", max);
for (int i = n - 2; i >= 0; i--) {
if (arr[i] > max) {
max = arr[i];
printf("%d ", max);
}
}
}

int main() {
int arr[] = {16, 17, 4, 3, 5, 2};
int n = 6;
printLeaders(arr, n);
return 0;
}

🔍 Problem Statement
A superior element in an array is one which is greater than all the elements to its right.
The rightmost element is always a superior element (since no elements exist to its right).

You are required to implement this logic inside the function:

int Find_Number_Of_Superior_Element(int[] arr, int n)

🧪 Sample Input & Output


Input:

n = 6
arr = [8, 10, 6, 2, 9, 7]

Superior Elements Identified:

●​ 10 (greater than 6, 2, 9, 7)​

●​ 9 (greater than 7)​

●​ 7 (last element)​

Output:

Number of Superior Elements: 3

🧠 Concept & Explanation


Instead of comparing every element with all elements to its right (which takes O(n²) time), we
can reduce it to O(n) by iterating from right to left, tracking the maximum value found so
far.

✅ Strategy:
●​ Traverse the array from the end to the beginning.​

●​ Keep track of the maximum element encountered (maxFromRight).​


●​ The current element is superior if it's greater than maxFromRight.​

●​ Update maxFromRight whenever a superior element is found.​

●​ Don’t forget: the last element is always superior.​

💡
💡
Java Implementation
Java Implementation
public class SuperiorElements {

public static int Find_Number_Of_Superior_Element(int[] arr, int n)


{
int count = 0;
int maxFromRight = arr[n - 1];
count++; // Last element is always superior

for (int i = n - 2; i >= 0; i--) {


if (arr[i] > maxFromRight) {
count++;
maxFromRight = arr[i];
}
}

return count;
}

public static void main(String[] args) {


int[] arr = {8, 10, 6, 2, 9, 7};
int n = [Link];

int result = Find_Number_Of_Superior_Element(arr, n);


[Link]("Number of Superior Elements: " + result);
}
}

🎂 Problem Statement
It's Edward's birthday, and his friends have surprised him with a huge circular cake.​
Edward wonders: "What’s the maximum number of pieces I can make using exactly N
straight cuts?"

Your task is to implement a function that returns this maximum number of cake pieces for a
given number of straight vertical cuts, N.

➕ Note:
●​ The answer can be very large, so return the result modulo 1000000007.​

🧠 Concept & Explanation


This is a classic geometrical and combinatorics problem.

🔍 Insight:
The maximum number of regions (pieces) you can divide a circle into using N straight cuts
(with optimal placement) follows the formula:

Maximum Pieces=N×(N+1)2+1\text{Maximum Pieces} = \frac{N \times (N + 1)}{2} +


1Maximum Pieces=2N×(N+1)​+1

This formula comes from adding the maximum number of new regions each new line
can introduce when it intersects all previous lines.

✅ Why It's Asked in Interviews


●​ Tests mathematical reasoning and understanding of patterns​

●​ Requires modular arithmetic handling​

●​ Helps interviewers assess optimization thinking​

💡 Java Implementation
public class CakeCuts {
static final int MOD = 1000000007;

public static int maxPieces(int N) {


long n = (long) N;
long result = ((n * (n + 1)) / 2) + 1;
return (int)(result % MOD);
}

public static void main(String[] args) {


int N = 5; // Example: 5 cuts
[Link]("Maximum Cake Pieces: " + maxPieces(N));
}
}

💡 C++ Implementation
#include <iostream>
using namespace std;

const int MOD = 1000000007;

int maxPieces(int N) {
long long n = (long long)N;
long long result = ((n * (n + 1)) / 2) + 1;
return result % MOD;
}

int main() {
int N = 5; // Example
cout << "Maximum Cake Pieces: " << maxPieces(N) << endl;
return 0;
}

🧪 Sample Input & Output


Input:
N = 5

Formula Calculation:

5×(5+1)2+1=302+1=15+1=16\frac{5 \times (5 + 1)}{2} + 1 = \frac{30}{2} + 1 = 15 + 1 =


1625×(5+1)​+1=230​+1=15+1=16

Output:

16

📘 What You Learn From This Problem


●​ Application of combinatorics formula in real-world scenarios​

●​ Efficiently solving without loops​

●​ Proper use of modulo arithmetic​

●​ Recognizing and handling large values safely​

✅ Output
Maximum Cake Pieces: 16

🔢 Problem Statement
You're given a number N, and your task is to reduce it to a single-digit number using a
specific set of operations. These operations are:
1.​ If N is odd, perform:​
N=⌊N2⌋N = \left\lfloor \frac{N}{2} \right\rfloorN=⌊2N​⌋
2.​ If N is even, perform:​
N=⌊N−22⌋N = \left\lfloor \frac{N - 2}{2} \right\rfloorN=⌊2N−2​⌋
3.​ If N is already a single-digit (0–9), return it as it is.​

Repeat the process until N becomes a single-digit number.

🧠 Concept & Explanation


This problem tests your understanding of:

●​ Conditional statements​

●​ Integer division (floor)​

●​ Looping until a termination condition is met​

🔄 Logic Flow:
●​ Keep applying the transformation based on whether the number is odd or even.​

●​ Stop when the number is less than 10.​

●​ Be cautious: since floor division is default in integer math, both Java and C++
handle this naturally.​

💡 Java Implementation
public class ReduceToSingleDigit {

public static int reduceToSingleDigit(int N) {


while (N >= 10) {
if (N % 2 == 0) {
N = (N - 2) / 2;
} else {
N = N / 2;
}
}
return N;
}

public static void main(String[] args) {


[Link]("Output 1: " + reduceToSingleDigit(25));
// Output: 6 → 3 → 1
[Link]("Output 2: " + reduceToSingleDigit(10));
// Output: 4
[Link]("Output 3: " + reduceToSingleDigit(5));
// Output: 5
}
}

💡 C++ Implementation
#include <iostream>
using namespace std;

int reduceToSingleDigit(int N) {
while (N >= 10) {
if (N % 2 == 0)
N = (N - 2) / 2;
else
N = N / 2;
}
return N;
}

int main() {
cout << "Output 1: " << reduceToSingleDigit(25) << endl; // 6 →
3 → 1
cout << "Output 2: " << reduceToSingleDigit(10) << endl; // 4
cout << "Output 3: " << reduceToSingleDigit(5) << endl; // 5
return 0;
}
🧪 Sample Input & Output
Example 1:

Input: N = 25​
Steps:

●​ 25 is odd → 25 / 2 = 12​

●​ 12 is even → (12 - 2) / 2 = 5​

●​ 5 is single-digit → Stop​
Output: 5​

Example 2:

Input: N = 10​
Steps:

●​ 10 is even → (10 - 2) / 2 = 4​

●​ 4 is single-digit → Stop​
Output: 4​

Example 3:

Input: N = 5​
Steps:

●​ 5 is already single-digit​
Output: 5​

🔠 Problem Statement
You're given a string of mixed-case alphabets, and your task is to convert the string
entirely to either:
●​ UPPERCASE, if the number of uppercase letters is greater​

●​ lowercase, otherwise.​

In case of a tie, lowercase is preferred.

🧠 Concept & Explanation


This problem checks your understanding of:

●​ Character traversal​

●​ Counting uppercase and lowercase letters​

●​ Conditional string transformation using basic logic.​

🔍 Strategy:
1.​ Traverse through the string character by character.​

2.​ Count:​

○​ How many uppercase letters exist.​

○​ How many lowercase letters exist.​

3.​ Compare the two counts:​

○​ If uppercaseCount > lowercaseCount, convert the whole string to


UPPERCASE.​

○​ Otherwise, convert the string to lowercase.​

💡 Java Implementation
public class ConvertCase {

public static String convertCase(String str) {


int upper = 0, lower = 0;

for (char c : [Link]()) {


if ([Link](c)) upper++;
else if ([Link](c)) lower++;
}

return (upper > lower) ? [Link]() :


[Link]();
}

public static void main(String[] args) {


[Link]("Output 1: " + convertCase("AbCdEfG"));
// Output: ABCDEFG
[Link]("Output 2: " + convertCase("xYz"));
// Output: xyz
}
}

💡 C++ Implementation
cpp

#include <iostream>
#include <string>
using namespace std;

string convertCase(string str) {


int upper = 0, lower = 0;

for (char c : str) {


if (isupper(c)) upper++;
else if (islower(c)) lower++;
}

if (upper > lower)


for (char &c : str) c = toupper(c);
else
for (char &c : str) c = tolower(c);
return str;
}

int main() {
cout << "Output 1: " << convertCase("AbCdEfG") << endl; //
Output: ABCDEFG
cout << "Output 2: " << convertCase("xYz") << endl; //
Output: xyz
return 0;
}

🧪 Sample Input & Output


Example 1:

●​ Input: "AbCdEfG"​

●​ Uppercase letters: 4​

●​ Lowercase letters: 3​

●​ Output: "ABCDEFG"​

Example 2:

●​ Input: "xYz"​

●​ Uppercase letters: 1​

●​ Lowercase letters: 2​

●​ Output: "xyz"​

✊🖐✌️ Problem Statement


Two players, A and B, are playing the classic game of Rock, Paper, Scissors.​
Player A makes a move represented by a string: "rock", "paper", or "scissor"
(case-insensitive).​
Your task is to determine the winning move for Player B, assuming they want to always
beat Player A.

✅ Rules Recap:
●​ Rock beats Scissors​

●​ Scissors beat Paper​

●​ Paper beats Rock​

🧠 Concept & Explanation


This problem involves simple string comparison and a fixed conditional mapping.

You just need to return the move that beats Player A’s move.

💡 Java Implementation
public class RockPaperScissors {

public static String winningMove(String A_move) {


A_move = A_move.toLowerCase();

switch (A_move) {
case "rock":
return "paper";
case "paper":
return "scissor";
case "scissor":
return "rock";
default:
return "Invalid move";
}
}

public static void main(String[] args) {


[Link]("Output 1: " + winningMove("rock"));
// Output: paper
[Link]("Output 2: " + winningMove("scissor"));
// Output: rock
}
}

💡 C++ Implementation
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

string winningMove(string A_move) {


transform(A_move.begin(), A_move.end(), A_move.begin(),
::tolower);

if (A_move == "rock")
return "paper";
else if (A_move == "paper")
return "scissor";
else if (A_move == "scissor")
return "rock";
else
return "Invalid move";
}

int main() {
cout << "Output 1: " << winningMove("rock") << endl; //
Output: paper
cout << "Output 2: " << winningMove("scissor") << endl; //
Output: rock
return 0;
}

🧪 Sample Input & Output


Example 1:
●​ Input: "rock"​

●​ Player A Move: Rock​

●​ Player B Should Play: Paper (since paper beats rock)​

●​ Output: paper​

Example 2:

●​ Input: "scissor"​

●​ Player A Move: Scissor​

●​ Player B Should Play: Rock (since rock beats scissor)​

●​ Output: rock​
🔢 Problem Statement
Alex has been given a number N, and he must determine how many Meta Numbers exist
from 1 to N.

🔎 Def tion of a Meta Number:


A number is called a Meta Number if:

●​ It is divisible by 1, 2, 4, and 8​

●​ It is NOT divisible by 10​

Your task is to write a function that returns the count of Meta Numbers between 1 and N
(inclusive).

🧠 Concept & Explanation


Let’s break down the def tion:

●​ A number divisible by 1, 2, 4, and 8 is essentially any number divisible by 8, because


if a number is divisible by 8, it's also divisible by 4, 2, and 1.​

●​ But it must NOT be divisible by 10.​

✅ So we only consider numbers that:


1.​ Are divisible by 8​

2.​ Are NOT divisible by 10​

🔄 Efficient Strategy:
Instead of looping from 1 to N and checking each number (which is inefficient for large N),
we:

1.​ Loop through all multiples of 8 up to N​


2.​ Check if the number is not divisible by 10​

3.​ Count such numbers​

This reduces time complexity to O(N/8), which is efficient up to N = 10⁹

💡 Java Implementation
public class MetaNumbers {

public static int countMetaNumbers(int N) {


int count = 0;
for (int i = 8; i <= N; i += 8) {
if (i % 10 != 0) {
count++;
}
}
return count;
}

public static void main(String[] args) {


int N = 20;
[Link]("Output: " + countMetaNumbers(N)); //
Output: 2

N = 13;
[Link]("Output: " + countMetaNumbers(N)); //
Output: 1
}
}

💡 C++ Implementation
#include <iostream>
using namespace std;

int countMetaNumbers(int N) {
int count = 0;
for (int i = 8; i <= N; i += 8) {
if (i % 10 != 0)
count++;
}
return count;
}

int main() {
int N;
cin >> N;
cout << countMetaNumbers(N) << endl;
return 0;
}

🧪 Sample Input & Output


Example 1:

Input: 20​
Multiples of 8 ≤ 20: 8, 16

●​ 8 % 10 ≠ 0 ✅​
●​ 16 % 10 ≠ 0 ✅​
Output: 2​

Example 2:

Input: 13​
Multiples of 8 ≤ 13: 8

●​ 8 % 10 ≠ 0 ​ ✅
Output: 1​

🌾 Problem Statement
You are given n farmers, each owning a certain number of lands, defined by a rule
involving XOR operation. The number of lands X owned by the i-th farmer is determined as:

Where:

●​ X₁ (first farmer) always owns 1 unit of land.​

●​ i is the 1-based index of the farmer.​

●​ For all i > 1:​

Your task is to compute the total number of lands owned by all n farmers combined.

🧠 Concept & Explanation


This problem revolves around:

●​ XOR (Exclusive OR) operation​

●​ Mainta ng cumulative logic​

●​ Using a loop to apply the relation to generate the full sequence​

✅ Key Understanding:
●​ XOR is a bitwise operation:​
A ^ B returns a number with bits set to 1 where A and B differ.​

●​ For n = 1, result = 1 (base case).​

For n = 3:​
X₁ = 1
X₂ = 1 ^ 2 = 3
X₃ = 3 ^ 3 = 0
Total = 1 + 3 + 0 = 4
💡 Java Implementation
public class FarmerLand {

public static int totalLandOwned(int n) {


int sum = 0;
int prev = 1;
sum += prev; // X1 is always 1

for (int i = 2; i <= n; i++) {


int current = prev ^ i;
sum += current;
prev = current;
}

return sum;
}

public static void main(String[] args) {


[Link]("Output for n=1: " + totalLandOwned(1));
// Output: 1
[Link]("Output for n=3: " + totalLandOwned(3));
// Output: 4
}
}

💡 C++ Implementation
t
#include <iostream>
using namespace std;

int totalLandOwned(int n) {
int sum = 0;
int prev = 1;
sum += prev;

for (int i = 2; i <= n; i++) {


int curr = prev ^ i;
sum += curr;
prev = curr;
}

return sum;
}

int main() {
cout << "Output for n=1: " << totalLandOwned(1) << endl; //
Output: 1
cout << "Output for n=3: " << totalLandOwned(3) << endl; //
Output: 4
return 0;
}

🧪 Sample Input & Output


Example 1:

Input: n = 1

●​ X₁ = 1​

●​ Output: 1​

Example 2:

Input: n = 3

●​ X₁ = 1​

●​ X₂ = 1 ^ 2 = 3​

●​ X₃ = 3 ^ 3 = 0​

●​ Output: 1 + 3 + 0 = 4​

🎓 Problem Statement
There are n students and a total of n × n seats arranged in a grid.​
Each row and each column can contain only one student, which means:

●​ No two students can sit in the same row​

●​ No two students can sit in the same column​

You are asked to find the total number of distinct seating arrangements for n students
that satisfy these conditions.

🧠 Concept & Explanation


This is a classic problem of counting permutations.

✅ Key Insight:
If there are n students and each must be placed:

●​ In a unique row​

●​ In a unique column​

This is equivalent to placing students such that no two share a row or a column, which
is exactly the def tion of a permutation of n elements.

💡 Therefore, the number of ways = n! (n factorial)


Example:

●​ For n = 1:​
→ Only 1 way → Output: 1​

●​ For n = 2:​
→ Students can be seated as:​

○​ [1,2]​

○​ [2,1]​
→ Total: 2 permutations → Output: 2​
🔢 Factorial Function with Modulo (for large n)
As n grows, n! grows very fast. For large values, we use:

●​ Efficient factorial calculation using loops​

●​ Modulo 10^9 + 7 to handle large numbers​

💡 Java Implementation
public class StudentSeating {

static final int MOD = 1000000007;

public static int numberOfWays(int n) {


long result = 1;
for (int i = 2; i <= n; i++) {
result = (result * i) % MOD; // you can ignore %MOD
here its only for large number
}
return (int) result;
}

public static void main(String[] args) {


[Link]("Output for N=1: " + numberOfWays(1)); //
Output: 1
[Link]("Output for N=2: " + numberOfWays(2)); //
Output: 2
[Link]("Output for N=5: " + numberOfWays(5)); //
Output: 120
}
}

💡 C++ Implementation
#include <iostream>
using namespace std;

const int MOD = 1000000007;

int numberOfWays(int n) {
long long result = 1;
for (int i = 2; i <= n; i++) {
result = (result * i) % MOD;
}
return result;
}

int main() {
cout << "Output for N=1: " << numberOfWays(1) << endl; //
Output: 1
cout << "Output for N=2: " << numberOfWays(2) << endl; //
Output: 2
cout << "Output for N=5: " << numberOfWays(5) << endl; //
Output: 120
return 0;
}

🧪 Sample Input & Output


Example 1:

Input: n = 1​
Output: 1

Example 2:

Input: n = 2

●​ Possible permutations: [1,2] and [2,1]​


Output: 2​

👥 Problem Statement
Alice is organizing a contest where each team consists of exactly 4 players.​
Players are of two types:

●​ Experienced​

●​ Freshers​

To ensure fairness, every team must include at least 1 experienced and 1 fresher.

You're given:

●​ N: Number of experienced players​

●​ M: Number of freshers​

Your task is to determine the maximum number of teams that can be formed such that:

●​ Each team has 4 members​

●​ Each team has at least 1 experienced and at least 1 fresher​

●​ No player is used in more than one team​

🧠 Concept & Explanation


Each team = 4 members​
Each team must have ≥1 experienced AND ≥1 fresher

So:

●​ The m mum number of people required per team = 4​

●​ You cannot make more than floor((N + M) / 4) teams overall​

●​ But also, you cannot make more teams than either the number of experienced or
freshers (because each team needs both)​

✅ Final Formula:
💡 Java Implementation
public class TeamFormation {

public static int maxTeams(int N, int M) {


int totalPlayers = N + M;
return [Link](totalPlayers / 4, [Link](N, M));
}

public static void main(String[] args) {


[Link]("Output (N=5, M=5): " + maxTeams(5, 5));
// Output: 2
[Link]("Output (N=3, M=5): " + maxTeams(3, 5));
// Output: 2
[Link]("Output (N=10, M=1): " + maxTeams(10,
1)); // Output: 1
}
}

💡 C++ Implementation
#include <iostream>
using namespace std;

int maxTeams(int N, int M) {


int total = N + M;
return min(total / 4, min(N, M));
}

int main() {
cout << "Output (N=5, M=5): " << maxTeams(5, 5) << endl; //
Output: 2
cout << "Output (N=3, M=5): " << maxTeams(3, 5) << endl; //
Output: 2
cout << "Output (N=10, M=1): " << maxTeams(10, 1) << endl; //
Output: 1
return 0;
}

🧪 Sample Input & Output


Test Case 1:

Input: N = 5, M = 5

●​ Total = 10​

●​ Max full teams = 10 / 4 = 2​

●​ Min(N, M) = 5​

●​ ✅ Max Teams = min(2, 5) = 2​


Output: 2

Test Case 2:

Input: N = 3, M = 5

●​ Total = 8 → 8 / 4 = 2​

●​ Min(N, M) = 3​

●​ ✅ Max Teams = min(2, 3) = 2​


Output: 2
🍀 Problem Statement
Rohan loves numbers made up only of digits 4 and 7. He calls them “lucky numbers.”

Some examples of lucky numbers:

●​ ✅ 4, 7, 44, 74, 477, 7744​


Not lucky:

●​ ❌ 5, 13, 467, 78​


Rohan also likes numbers that are divisible by any lucky number. He calls these "almost
lucky numbers."

Your Task:

Write a program to determine if a given number N is almost lucky — meaning it can be


evenly divided by at least one lucky number.

🧠 Concept & Explanation


Step-by-step:

1.​ Generate all lucky numbers ≤ N​

2.​ Check if N % luckyNumber == 0 for any of them​

3.​ If yes, print YES → it is almost lucky​

4.​ If no, print NO​

💡 Java Implementation
import [Link].*;

public class AlmostLuckyNumber {


// Generate all lucky numbers up to N using recursion
static void generateLuckyNumbers(long current, long limit,
List<Long> luckyList) {
if (current > limit) return;
if (current != 0) [Link](current);

generateLuckyNumbers(current * 10 + 4, limit, luckyList);


generateLuckyNumbers(current * 10 + 7, limit, luckyList);
}

public static String isAlmostLucky(long N) {


List<Long> luckyNumbers = new ArrayList<>();
generateLuckyNumbers(0, N, luckyNumbers);

for (Long lucky : luckyNumbers) {


if (N % lucky == 0) return "YES";
}
return "NO";
}

public static void main(String[] args) {


long N = 47;
[Link]("Is " + N + " almost lucky? → " +
isAlmostLucky(N)); // Output: YES

N = 78;
[Link]("Is " + N + " almost lucky? → " +
isAlmostLucky(N)); // Output: NO
}
}

💡 C++ Implementation
#include <iostream>
#include <vector>
using namespace std;
void generateLuckyNumbers(long long current, long long limit,
vector<long long>& lucky) {
if (current > limit) return;
if (current != 0) lucky.push_back(current);

generateLuckyNumbers(current * 10 + 4, limit, lucky);


generateLuckyNumbers(current * 10 + 7, limit, lucky);
}

string isAlmostLucky(long long N) {


vector<long long> lucky;
generateLuckyNumbers(0, N, lucky);

for (long long l : lucky) {


if (N % l == 0) return "YES";
}
return "NO";
}

int main() {
long long N;
cin >> N;
cout << isAlmostLucky(N) << endl;
return 0;
}

🧪 Sample Input & Output


Example 1:

Input: N = 47

●​ 47 is a lucky number → divides itself​


Output: YES

Example 2:

Input: N = 78

●​ Not divisible by 4, 7, 44, 47, etc.​


Output: NO
🔢 Problem Statement
You’re given an array of N elements, where each element is either 5 or 0.

Your task is to form the largest possible number using some or all elements of the array
and rearrange them such that:

●​ The number is divisible by 90

🧠 Rules for Divisibility


To be divisible by:

✅ 10 → Number must end in 0


✅ 9 → Sum of digits must be divisible by 9
So, for divisibility by 90:

●​ At least one 0 must be present​

●​ The sum of digits must be divisible by 9

🧠 Strategy
1.​ Count number of 5s and number of 0s in the array.​

2.​ If no 0s → Not divisible by 10 → Output: -1​

3.​ To satisfy divisible by 9, sum of digits must be divisible by 9. Since each 5 adds 5 to
the sum, we need the count of 5s to be a multiple of 9.​

4.​ Use the maximum number of 5s (in multiples of 9) and at least one 0, then
append 0s at the end.

✅ Java Implementation
public class LargestDivisibleBy90 {
public static String largestNumber(int[] arr) {
int count5 = 0, count0 = 0;
for (int num : arr) {
if (num == 5) count5++;
else if (num == 0) count0++;
}

if (count0 == 0) return "-1"; // No 0 to end the number


if (count5 < 9) return "0"; // Not enough 5s for sum % 9
== 0

count5 = (count5 / 9) * 9; // Use maximum multiple of 9 5s

StringBuilder sb = new StringBuilder();


for (int i = 0; i < count5; i++) [Link]("5");
for (int i = 0; i < count0; i++) [Link]("0");

return [Link]();
}

public static void main(String[] args) {


int[] arr1 = {5, 5, 5, 5, 5, 5, 5, 5, 0, 5, 5};
[Link]("Output: " + largestNumber(arr1)); //
Output: 5555555550

int[] arr2 = {5, 0};


[Link]("Output: " + largestNumber(arr2)); //
Output: 0
}
}

✅ C++ Implementation
#include <iostream>
#include <vector>
#include <string>
using namespace std;

string largestNumber(vector<int>& arr) {


int count5 = 0, count0 = 0;
for (int num : arr) {
if (num == 5) count5++;
else if (num == 0) count0++;
}

if (count0 == 0) return "-1";


if (count5 < 9) return "0";

count5 = (count5 / 9) * 9;
string result(count5, '5');
[Link](count0, '0');

return result;
}

int main() {
vector<int> arr1 = {5, 5, 5, 5, 5, 5, 5, 5, 0, 5, 5};
cout << "Output: " << largestNumber(arr1) << endl; // Output:
5555555550

vector<int> arr2 = {5, 0};


cout << "Output: " << largestNumber(arr2) << endl; // Output: 0

return 0;
}

🧪 Sample Input & Output


Example 1:Input: {5, 5, 5, 5, 5, 5, 5, 5, 0, 5, 5}

●​ 5 appears 10 times → max 9 used​

●​ 0 appears 1 time → good​

●​ Output: 5555555550

Example 2:Input: {5, 0}

●​ Only one 5 → can't make sum divisible by 9​

●​ Output: 0
🧗‍♂️ Problem Statement
There are n stairs. A person standing at the bottom wants to reach the top.

The person can climb:

●​ Either 1 stair at a time​

●​ Or 2 stairs at a time​

Your task is to count the number of distinct ways the person can reach the top.​
Note: The order of steps matters.

🧠 Concept & Explanation


This is a classic Dynamic Programming or Fibonacci problem.

Let:

●​ ways(n) be the number of ways to reach the n-th stair.​

The recurrence relation is:


ways(n)=ways(n−1)+ways(n−2)\text{ways}(n) = \text{ways}(n - 1) + \text{ways}(n -
2)ways(n)=ways(n−1)+ways(n−2)

Why?

●​ To reach n, the person can either:​

○​ Come from step n-1 using 1 step​

○​ Come from step n-2 using 2 steps​

Base Cases:

●​ ways(0) = 1 (1 way: doing nothing)​

●​ ways(1) = 1 (Only one way to reach first stair)​

●​ ways(2) = 2 (Two ways: 1+1 or 2)

💡 Java Implementation
public class StairClimbing {

public static int countWays(int n) {


if (n <= 1) return 1;

int[] dp = new int[n + 1];


dp[0] = 1; // 1 way to stay at bottom
dp[1] = 1; // 1 way to reach step 1

for (int i = 2; i <= n; i++) {


dp[i] = dp[i - 1] + dp[i - 2];
}

return dp[n];
}

public static void main(String[] args) {


[Link]("Ways to climb 1 stair: " +
countWays(1)); // Output: 1
[Link]("Ways to climb 2 stairs: " +
countWays(2)); // Output: 2
[Link]("Ways to climb 4 stairs: " +
countWays(4)); // Output: 5
}
}

💡 C++ Implementation
#include <iostream>
using namespace std;

int countWays(int n) {
if (n <= 1) return 1;

int dp[n + 1];


dp[0] = 1; // Staying at the base
dp[1] = 1; // Only one way to climb 1 stair

for (int i = 2; i <= n; i++) {


dp[i] = dp[i - 1] + dp[i - 2];
}

return dp[n];
}

int main() {
cout << "Ways to climb 1 stair: " << countWays(1) << endl; //
Output: 1
cout << "Ways to climb 2 stairs: " << countWays(2) << endl; //
Output: 2
cout << "Ways to climb 4 stairs: " << countWays(4) << endl; //
Output: 5
return 0;
}

🧪 Sample Input & Output


Example 1:

Input: n = 4​
Output: 5​
Ways:

●​ 1 + 1 + 1 + 1​

●​ 1 + 2 + 1​

●​ 1 + 1 + 2​

●​ 2 + 1 + 1​

●​ 2 + 2​

Example 2:

Input: n = 1​
Output: 1

Example 3:

Input: n = 2​
Output: 2​
(1+1) and (2)
💡 Problem Statement
You have n bulbs, all tially OFF.​
You perform n rounds of toggling:

●​ In round 1: Toggle every bulb (so all turn ON)​

●​ In round 2: Toggle every 2nd bulb​

●​ In round 3: Toggle every 3rd bulb​

●​ ...​

●​ In round i: Toggle every i-th bulb​

●​ In round n: Only the n-th bulb is toggled​

Goal: After n rounds, how many bulbs are ON?

🧠 Concept & Explanation


This is a mathematics + logic puzzle.

Each bulb is toggled in every round where its position number is divisible by that round
number.

So, bulb k is toggled once for every divisor of k.

✅ Observation:
●​ If a number has an even number of divisors, it will end up OFF​

●​ If a number has an odd number of divisors, it will end up ON​

But only perfect squares have odd number of divisors!

Why?

●​ Divisors usually come in pairs: e.g., 12 → (1,12), (2,6), (3,4) → even count​

●​ But perfect squares like 9 → (1,9), (3,3) → 3 only counted once → odd number​
✅ Final Insight:
👉 The number of bulbs that remain ON = Number of perfect squares ≤ n
Answer=⌊n⌋\text{Answer} = \lfloor \sqrt{n} \rfloorAnswer=⌊n​⌋

🧪 Sample Inputs & Outputs


Input: n = 1


Perfect squares ≤ 1 → {1}​
Output: 1

Input: n = 3


Perfect squares ≤ 3 → {1}​
Output: 1

Input: n = 10


Perfect squares ≤ 10 → {1, 4, 9}​
Output: 3

💻 Java Implementation
public class BulbSwitcher {

public static int countBulbsOn(int n) {


return (int) [Link](n);
}

public static void main(String[] args) {


[Link]("Bulbs ON for n=1: " + countBulbsOn(1));
// Output: 1
[Link]("Bulbs ON for n=3: " + countBulbsOn(3));
// Output: 1
[Link]("Bulbs ON for n=10: " +
countBulbsOn(10)); // Output: 3
}
}
💻 C++ Implementation
#include <iostream>
#include <cmath>
using namespace std;

int countBulbsOn(int n) {
return (int) sqrt(n);
}

int main() {
cout << "Bulbs ON for n=1: " << countBulbsOn(1) << endl; //
Output: 1
cout << "Bulbs ON for n=3: " << countBulbsOn(3) << endl; //
Output: 1
cout << "Bulbs ON for n=10: " << countBulbsOn(10) << endl; //
Output: 3
return 0;
}

📘 What You Learn From This Problem


●​ How toggling behavior links to number theory​

●​ Understanding factors and divisors​

●​ Identifying perfect squares in logical problems​

✅ Output Summary
Input: 1 → Output: 1
Input: 3 → Output: 1
Input: 10 → Output: 3
Input: 100 → Output: 10
🎯 Problem Statement
Given an array of integers and a number sum, print all pairs in the array whose sum is
equal to sum.

Note: The order of pairs matters only in terms of positions. If the same number
appears multiple times, all valid combinations should be shown.

🧠 Example
Input 1:

arr[] = {1, 5, 7, -1, 5}


sum = 6

Output:

(1, 5)
(7, -1)
(1, 5)

Input 2:

arr[] = {2, 5, 17, -1}


sum = 7

Output:

(2, 5)

🔍 Approach
There are two ways to approach this:

✅ Method 1: Brute Force (Nested Loop)


●​ Time Complexity: O(n²)​

●​ Check all pairs one by one​

✅ Method 2: HashMap (Efficient)


●​ Time Complexity: O(n)​

●​ Use a HashMap to store counts of elements​

●​ For each element, check if sum - element exists​

💻 Java Implementation (Brute Force)


public class PairSumFinder {

public static void printPairs(int[] arr, int sum) {


int n = [Link];
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] + arr[j] == sum) {
[Link]("(" + arr[i] + ", " + arr[j]
+ ")");
}
}
}
}

public static void main(String[] args) {


int[] arr1 = {1, 5, 7, -1, 5};
int sum1 = 6;
[Link]("Output for Input 1:");
printPairs(arr1, sum1); // Output: (1,5) (7,-1) (1,5)

int[] arr2 = {2, 5, 17, -1};


int sum2 = 7;
[Link]("Output for Input 2:");
printPairs(arr2, sum2); // Output: (2,5)
}
}

💻 C++ Implementation (Brute Force)


#include <iostream>
using namespace std;

void printPairs(int arr[], int n, int sum) {


for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
if (arr[i] + arr[j] == sum) {
cout << "(" << arr[i] << ", " << arr[j] << ")" <<
endl;
}
}
}
}

int main() {
int arr1[] = {1, 5, 7, -1, 5};
int sum1 = 6;
cout << "Output for Input 1:" << endl;
printPairs(arr1, 5, sum1); // Output: (1,5) (7,-1) (1,5)

int arr2[] = {2, 5, 17, -1};


int sum2 = 7;
cout << "Output for Input 2:" << endl;
printPairs(arr2, 4, sum2); // Output: (2,5)

return 0;
}

🧪 Sample Input & Output


Example 1:

Input: arr[] = {1, 5, 7, -1, 5}, sum = 6​


Output:
(1, 5)
(7, -1)
(1, 5)

Example 2:

Input: arr[] = {2, 5, 17, -1}, sum = 7​


Output:

(2, 5)

✅ Q: Find All Pairs with Given Sum


✅ Question:​
Given an array and a value, find all pairs whose sum is equal to the given value.

✅ Explanation:​
Use a nested loop to check all pairs. For each element, check if another element exists that
sums to the given value.

✅ Input:

arr[] = {1, 5, 7, -1, 5}, sum = 6

✅ Output:
s

(1,5), (7,-1), (1,5)

✅ Java Code
java

public class PairSum {


public static void main(String[] args) {
int[] arr = {1, 5, 7, -1, 5};
int sum = 6;
findPairs(arr, sum);
}

public static void findPairs(int[] arr, int sum) {


for (int i = 0; i < [Link]; i++) {
for (int j = i + 1; j < [Link]; j++) {
if (arr[i] + arr[j] == sum)
[Link]("(" + arr[i] + "," + arr[j] +
")");
}
}
}
}

✅ C Code
c

#include <stdio.h>

void findPairs(int arr[], int n, int sum) {


for (int i = 0; i < n; i++)
for (int j = i + 1; j < n; j++)
if (arr[i] + arr[j] == sum)
printf("(%d,%d)\n", arr[i], arr[j]);
}

int main() {
int arr[] = {1, 5, 7, -1, 5};
int sum = 6;
int n = sizeof(arr)/sizeof(arr[0]);
findPairs(arr, n, sum);
return 0;
}

✅ Q: Find the Element that Appears Once (All others appear twice)
✅ Explanation:​
Use XOR. XOR of a number with itself is 0, and XOR of a number with 0 is the number
itself.
✅ Input:
arr[] = {2, 3, 5, 4, 5, 3, 4}

✅ Output:
2

✅ Java Code
java

public class SingleElement {


public static void main(String[] args) {
int[] arr = {2, 3, 5, 4, 5, 3, 4};
int res = 0;
for (int num : arr) res ^= num;
[Link](res);
}
}

✅ C Code
c

#include <stdio.h>

int findSingle(int arr[], int n) {


int res = 0;
for (int i = 0; i < n; i++)
res ^= arr[i];
return res;
}

int main() {
int arr[] = {2, 3, 5, 4, 5, 3, 4};
int n = sizeof(arr)/sizeof(arr[0]);
printf("%d\n", findSingle(arr, n));
return 0;
}

✅ Q: Find Maximum Product of Two Integers


✅ Input:
arr[] = {1, 20, 30, 4, 50}

✅ Output:
s

1500 (30 * 50)

✅ Java Code
java

import [Link];
public class MaxProduct {
public static void main(String[] args) {
int[] arr = {1, 20, 30, 4, 50};
[Link](arr);
int n = [Link];
[Link](arr[n - 1] * arr[n - 2]);
}
}

✅ C Code
c

#include <stdio.h>
#include <stdlib.h>

int compare(const void* a, const void* b) {


return (*(int*)a - *(int*)b);
}
int main() {
int arr[] = {1, 20, 30, 4, 50};
int n = sizeof(arr) / sizeof(arr[0]);
qsort(arr, n, sizeof(int), compare);
printf("%d\n", arr[n - 1] * arr[n - 2]);
return 0;
}

✅ Q: Count Occurrences of a Number in a Sorted Array


✅ Input:
arr[] = {1, 2, 2, 2, 3, 4, 5}, key = 2

✅ Output:
3

✅ Java Code
java

public class CountOccurrence {


public static void main(String[] args) {
int[] arr = {1, 2, 2, 2, 3, 4, 5};
int key = 2, count = 0;
for (int num : arr)
if (num == key) count++;
[Link](count);
}
}

✅ C Code
c

#include <stdio.h>
int main() {
int arr[] = {1, 2, 2, 2, 3, 4, 5};
int n = 7, key = 2, count = 0;
for (int i = 0; i < n; i++)
if (arr[i] == key) count++;
printf("%d\n", count);
return 0;
}

✅ Q: Left Rotate an Array by 1


✅ Input:
arr[] = {1, 2, 3, 4, 5}

✅ Output:

[2, 3, 4, 5, 1]

✅ Java Code
java

public class LeftRotate {


public static void main(String[] args) {
int[] arr = {1, 2, 3, 4, 5};
int first = arr[0];
for (int i = 0; i < [Link] - 1; i++)
arr[i] = arr[i + 1];
arr[[Link] - 1] = first;

for (int num : arr) [Link](num + " ");


}
}

✅ C Code
c

#include <stdio.h>

int main() {
int arr[] = {1, 2, 3, 4, 5};
int n = 5, i, first = arr[0];

for (i = 0; i < n - 1; i++)


arr[i] = arr[i + 1];
arr[n - 1] = first;

for (i = 0; i < n; i++)


printf("%d ", arr[i]);

return 0;
}
🍫 Problem Statement
You're given:

●​ An array A[] of N positive integers, where each integer represents the number of
chocolates in a packet.​

●​ An integer M which represents the number of students.​

The task is to distribute packets to M students, one packet per student, such that the
difference between the maximum and m mum chocolates among selected packets is
m mized.

🧠 Key Insight
You want to choose M elements from the array such that:

max(selected)−min(selected)\text{max(selected)} -
\text{min(selected)}max(selected)−min(selected)

is as small as possible.

✅ Strategy
1.​ Sort the array​

2.​ Use a sliding window of size M to check all possible groups of M packets​

3.​ In each window, calculate:​


difference=A[i+M−1]−A[i]\text{difference} = A[i + M - 1] - A[i]difference=A[i+M−1]−A[i]
4.​ Keep track of the m mum difference​

💡 Java Implementation
import [Link];

public class ChocolateDistribution {


public static int minDiff(int[] A, int N, int M) {
if (M == 0 || N == 0) return 0;
if (M > N) return -1; // Not enough packets

[Link](A);

int minDiff = Integer.MAX_VALUE;


for (int i = 0; i + M - 1 < N; i++) {
int diff = A[i + M - 1] - A[i];
if (diff < minDiff) {
minDiff = diff;
}
}

return minDiff;
}

public static void main(String[] args) {


int[] A = {3, 4, 1, 9, 7, 1, 9, 12};
int N = [Link];
int M = 5;
[Link]("M mum difference: " + minDiff(A, N,
M)); // Output: 6
}
}

💡 C++ Implementation
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;

int minDiff(vector<int>& A, int M) {


int N = [Link]();
if (M == 0 || N == 0) return 0;
if (M > N) return -1;
sort([Link](), [Link]());

int minDiff = INT_MAX;


for (int i = 0; i + M - 1 < N; i++) {
int diff = A[i + M - 1] - A[i];
minDiff = min(minDiff, diff);
}

return minDiff;
}

int main() {
vector<int> A = {3, 4, 1, 9, 7, 1, 9, 12};
int M = 5;
cout << "M mum difference: " << minDiff(A, M) << endl; //
Output: 6
return 0;
}

🧪 Sample Input & Output


Example:

Input:

N = 8, M = 5
A = [3, 4, 1, 9, 7, 1, 9, 12]

Sorted A: [1, 1, 3, 4, 7, 9, 9, 12]


Best 5 packets: [3, 4, 7, 9, 9] → min=3, max=9​
Output: 6
🤖 Problem Statement
A round number (also called a happy number) is defined by a mathematical process:

1.​ Start with any positive integer n​

2.​ Replace the number by the sum of the squares of its digits​

3.​ Repeat the process​

4.​ If it eventually reaches 1, it’s called a happy number (round number)​

5.​ If it loops endlessly in a cycle that never includes 1, it’s not a happy number​

🧠
Your task:​
Write a program to determine whether a given number is a round (happy) number.

📥 Input
●​ An integer n (e.g., 19)​

📤 Output
●​ Return true if it's a round (happy) number, else false​

📚 Example
Input: n = 19​
Process:

1² + 9² = 82
8² + 2² = 68
6² + 8² = 100
1² + 0² + 0² = 1 ✅
Output: true
💡 Approach
To detect a cycle, we use a Set to keep track of previously seen numbers. If a number
repeats, it’s a cycle (not happy). If we reach 1, it's a happy number.

✅ Java Implementation
import [Link].*;

public class RoundNumber {

public static boolean isHappy(int n) {


Set<Integer> seen = new HashSet<>();
while (n != 1 && ![Link](n)) {
[Link](n);
n = getSquareSum(n);
}
return n == 1;
}

private static int getSquareSum(int n) {


int sum = 0;
while (n > 0) {
int digit = n % 10;
sum += digit * digit;
n /= 10;
}
return sum;
}

public static void main(String[] args) {


int n = 19;
[Link]("Is " + n + " a round number? " +
isHappy(n)); // Output: true
}
}
✅ C++ Implementation
#include <iostream>
#include <unordered_set>
using namespace std;

int getSquareSum(int n) {
int sum = 0;
while (n > 0) {
int digit = n % 10;
sum += digit * digit;
n /= 10;
}
return sum;
}

bool isHappy(int n) {
unordered_set<int> seen;
while (n != 1 && [Link](n) == [Link]()) {
[Link](n);
n = getSquareSum(n);
}
return n == 1;
}

int main() {
int n = 19;
cout << "Is " << n << " a round number? " << (isHappy(n) ?
"true" : "false") << endl; // Output: true
return 0;
}

🧪 More Examples
Input: n = 2

Process:

2² = 4
4² = 16
1² + 6² = 37
3² + 7² = 58
5² + 8² = 89
8² + 9² = 145
...
(loops forever)

Output: false
🏗️ Problem Statement
A startup is planning to expand its empire, and the CEO has shortlisted several land plots.​
Your job is to identify which of the shortlisted plots are perfect squares (i.e., their area
is a perfect square)—these are suitable for constructing new office buildings.

📥 Input
●​ First line: An integer N (the number of plots)​

●​ Second line: N space-separated integers representing areas of the plots​

📤 Output
●​ A single integer: the number of square-shaped plots​

✅ Example
Input:

6
64 16 38 81 50 100

Output:

Explanation:​
The perfect square plots are:

●​ 64 → 8×8​

●​ 16 → 4×4​

●​ 81 → 9×9​
●​ 100 → 10×10 ✅​
So, total = 4 square-shaped plots, but your sample output says 3 — possibly a typo.

🧠 Approach
1.​ Loop through each area.​

2.​ Check if its square root is an integer.​

3.​ Count such numbers.​

To check if a number is a perfect square, we can:

●​ Take its square root​

●​ Check if square of the floor of square root equals the number​

💻 Java Implementation
public class SquarePlots {

public static int countSquarePlots(int[] plots) {


int count = 0;
for (int area : plots) {
int sqrt = (int) [Link](area);
if (sqrt * sqrt == area) {
count++;
}
}
return count;
}

public static void main(String[] args) {


int[] plots = {64, 16, 38, 81, 50, 100};
[Link]("Number of square-shaped plots: " +
countSquarePlots(plots)); // Output: 4
}
}

💻 C++ Implementation
#include <iostream>
#include <cmath>
using namespace std;

int countSquarePlots(int arr[], int n) {


int count = 0;
for (int i = 0; i < n; i++) {
int root = sqrt(arr[i]);
if (root * root == arr[i]) {
count++;
}
}
return count;
}

int main() {
int arr[] = {64, 16, 38, 81, 50, 100};
int n = sizeof(arr)/sizeof(arr[0]);
cout << "Number of square-shaped plots: " <<
countSquarePlots(arr, n) << endl; // Output: 4
return 0;
}

🧪 More Test Cases


Test Case 1:

Input: 5
1 2 3 4 5
Output: 2 → (1, 4)
Test Case 2:

Input: 3
25 36 40
Output: 2 → (25, 36)

✅ Q: Number Triangle Pattern


✅ Input:

n = 4

✅ Output:

1
12
123
1234

✅ Java Code
java

public class Pattern2 {


public static void main(String[] args) {
int n = 4;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++)
[Link](j);
[Link]();
}
}
}

✅ C Code
c

#include <stdio.h>
int main() {
int n = 4;
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= i; j++)
printf("%d", j);
printf("\n");
}
return 0;
}

✅ Q: Inverted Star Pattern


✅ Input:

n = 5

✅ Output:

*****
****
***
**
*

✅ Java Code
java

public class Pattern3 {


public static void main(String[] args) {
int n = 5;
for (int i = n; i >= 1; i--) {
for (int j = 1; j <= i; j++)
[Link]("*");
[Link]();
}
}
}

✅ C Code
c

#include <stdio.h>
int main() {
int n = 5;
for (int i = n; i >= 1; i--) {
for (int j = 1; j <= i; j++)
printf("*");
printf("\n");
}
return 0;
}

✅ Q: Right-Aligned Star Pattern


✅ Input:

n = 5

✅ Output:

*
**
***
****
*****

✅ Java Code
java
public class Pattern4 {
public static void main(String[] args) {
int n = 5;
for (int i = 1; i <= n; i++) {
for (int s = i; s < n; s++)
[Link](" ");
for (int j = 1; j <= i; j++)
[Link]("*");
[Link]();
}
}
}

✅ C Code
c

#include <stdio.h>
int main() {
int n = 5;
for (int i = 1; i <= n; i++) {
for (int s = i; s < n; s++)
printf(" ");
for (int j = 1; j <= i; j++)
printf("*");
printf("\n");
}
return 0;
}

✅ Q: Pyramid Pattern with Stars


✅ Input:

n = 4

✅ Output:
*
***
*****
*******

✅ Java Code
java

public class Pattern5 {


public static void main(String[] args) {
int n = 4;
for (int i = 1; i <= n; i++) {
for (int s = i; s < n; s++)
[Link](" ");
for (int j = 1; j <= (2 * i - 1); j++)
[Link]("*");
[Link]();
}
}
}

✅ C Code
c

#include <stdio.h>
int main() {
int n = 4;
for (int i = 1; i <= n; i++) {
for (int s = i; s < n; s++)
printf(" ");
for (int j = 1; j <= (2 * i - 1); j++)
printf("*");
printf("\n");
}
return 0;
}

You might also like