ARRAYS
EASY
Q1: Largest Element in an Array
Problem Statement: -
Ankit is analysing performance scores of players stored in an array. He wants to
find the highest score among them to declare the best performer.
Input format:-
First line contains an integer N, the number of elements in the array.
Second line contains N space-separated integers representing the array.
Output format:-
A single integer which is the largest element in the array.
Test Case:
Input:
6
372941
Output:
9
Explanation:
Among the array elements [3, 7, 2, 9, 4, 1], the largest element is 9.
Algorithm:
1. Accept input N (size of the array).
2. Accept the array of N integers.
3. Initialize a variable max_val with the first element of the array.
4. Traverse through the array from the second element to the last:
o For each element, check if it is greater than max_val.
o If true, update max_val with this element.
5. After the loop ends, print max_val as the largest element.
Q2: Second Largest Element in an Array without Sorting
Problem Statement:-
Sneha is comparing sales figures of different stores. She wants to know not just
the best-performing store, but the second best. Help her find the second largest
value in the array of sales, without sorting.
Input format:-
First line contains an integer N (N >= 2).
Second line contains N space-separated integers.
Output format:-
A single integer representing the second largest element in the array.
Test Case:
Input:
5
41937
Output:
7
Explanation:
The array is [4, 1, 9, 3, 7]. Largest is 9. Second largest is 7.
Algorithm:
1. Accept input N (number of elements).
2. Accept the array elements.
3. Initialize two variables first and second as the smallest possible integers.
4. Loop through each element:
o If current > first:
Set second = first
Set first = current
o Else if current > second and current != first:
Set second = current
5. After loop, print second.
Q3: Check if the Array is Sorted
Problem Statement:-
A teacher arranged student scores in ascending order. A student wants to verify
if the scores are indeed sorted. Help them determine if the array is sorted in non-
decreasing order.
Input format:-
First line contains integer N.
Second line has N space-separated integers.
Output format:-
Print "Yes" if sorted, otherwise "No".
Test Case:
Input:
4
1234
Output:
Yes
Explanation:
All elements are in increasing order. So, the output is Yes.
Algorithm:
1. Accept N (number of elements).
2. Read the array elements.
3. Loop from i = 1 to N-1:
o If arr[i] <arr[i-1], print "No" and exit.
4. If loop completes, print "Yes".
Q4: Remove Duplicates from Sorted Array
Problem Statement:-
Rekha maintains sorted lists of IDs. She wants to clean the list by removing
duplicate IDs while preserving order. Help her create a new list with only unique
elements.
Input format:-
First line contains N
Second line contains N sorted space-separated integers
Output format:-
Print space-separated unique elements
Test Case:
Input:
7
1122334
Output:
1234
Explanation:
Repeated IDs are removed to form [1, 2, 3, 4]
Algorithm:
1. Accept N and the array.
2. Initialize empty list result.
3. Loop through array:
o If element is not same as previous (or it's the first), append to
result.
4. Print result list.
Q5: Left Rotate an Array by One Place
Problem Statement:-
Suresh wants to perform a left rotation on a set of sensor readings to align them
with his reference model. Help him rotate the array by one position to the left.
Input format:-
First line: N (number of elements)
Second line: N space-separated integers
Output format:-
Rotated array by one position
Test Case:
Input:
5
10 20 30 40 50
Output:
20 30 40 50 10
Explanation:
First element is moved to the end.
Algorithm:
1. Accept input N and array.
2. Store first element.
3. Shift all elements one index to the left.
4. Assign the first element to the last position.
5. Print the modified array.
Q6: Left Rotate an Array by D Places
Problem Statement:-
Nikhil wants to shift the elements of his log data by D timestamps to match a
specific reference point. Help him perform D left rotations on the array.
Input format:-
First line: Two integers N and D
Second line: N space-separated integers
Output format:-
Array after rotating left by D positions
Test Case:
Input:
5 2 10 20 30 40 50
Output:
30 40 50 10 20
Explanation:
First two elements moved to the end.
Algorithm:
1. Accept N and D.
2. Accept array of N elements.
3. Slice the array from D to end and 0 to D.
4. Concatenate the slices and print.
Q7: Move Zeros to End
Problem Statement:-
Kavya is analyzing user click logs. Zeros represent inactivity. Help her move all
inactive periods (zeros) to the end while keeping other activities in order.
Input format:-
First line: N
Second line: N space-separated integers
Output format:-
Array with all zeros moved to the end
Test Case:
Input:
6
0 1 0 3 12 0
Output:
1 3 12 0 0 0
Explanation:
All non-zero elements moved forward; zeros pushed back.
Algorithm:
1. Accept input N and array.
2. Initialize pos = 0.
3. Traverse array:
o If element is not zero, move it to index pos, increment pos.
4. Fill rest of array from pos with zeros.
Q8: Linear Search
Problem Statement:-
A shopkeeper searches for a product by ID in the stock list. Help him locate the
position of the product using linear search.
Input format:-
First line: N
Second line: N space-separated integers
Third line: Integer key to search
Output format:-
Index (0-based) of key if found, else -1
Test Case:
Input:
542713
7
Output:
2
Explanation:
Element 7 is at index 2.
Algorithm:
1. Accept input N, array and key.
2. Loop from i = 0 to N-1:
o If arr[i] == key, print i and return.
3. If not found, print -1.
Q9: Find the Union of Two Arrays
Problem Statement:-
Two departments submitted their employee ID lists. You need to compile a
master list of all unique IDs.
Input format:-
First line: Two integers n and m
Second line: n space-separated integers
Third line: m space-separated integers
Output format:-
Print union of both arrays with unique elements
Test Case:
Input:
54123452367
Output:
1234567
Explanation:
Combined unique elements from both lists.
Algorithm:
1. Accept n and m, and the arrays.
2. Create a set and add all elements from both arrays.
3. Print elements of the set in sorted or insertion order.
Q10: Find Missing Number in an Array
Problem Statement:-
A list of student roll numbers is supposed to be continuous from 1 to N. Due to a
technical issue, one roll number is missing. Help the admin find the missing roll
number.
Input format:-
First line: Integer N (the range is from 1 to N)
Second line: N-1 space-separated integers representing the roll numbers
Output format:-
A single integer representing the missing number
Test Case:
Input:
5
1235
Output:
4
Explanation:
Numbers from 1 to 5 should be present. 4 is missing.
Algorithm:
1. Accept N and the array.
2. Calculate total = N*(N+1)/2.
3. Calculate sum of elements in array.
4. The missing number = total - sum of array.
5. Print the missing number.
Q11: Maximum Consecutive Ones
Problem Statement:-
Vikas is monitoring a binary signal stream. He wants to find the maximum
number of consecutive 1s in the signal.
Input format:-
First line: Integer N
Second line: N space-separated binary digits (0s and 1s)
Output format:-
Maximum number of consecutive 1s
Test Case:
Input:
8
11011101
Output:
3
Explanation:
The longest sequence of 1s is of length 3.
Algorithm:
1. Accept input N and array.
2. Initialize count = 0, max_count = 0.
3. Traverse the array:
o If element is 1, increment count.
o If element is 0, reset count to 0.
o Update max_count if count >max_count.
4. Print max_count.
Q12: Find the Number that Appears Once, Others Twice
Problem Statement:-
In a system logging repeated error codes, one unique error appears only once
while others appear exactly twice. Help the engineer identify the unique error
code.
Input format:-
First line: Integer N
Second line: N space-separated integers where one number appears once,
others twice
Output format:-
The single unique number
Test Case:
Input:
5
23532
Output:
5
Explanation:
Numbers 2 and 3 appear twice. 5 appears once.
Algorithm:
1. Accept input N and array.
2. Initialize result = 0.
3. Traverse array:
o XOR each element with result.
4. Print result (XOR of duplicates cancels out, leaving unique).
Q13: Longest Subarray with Given Sum K (Positives Only)
Problem Statement:-
Sita is tracking daily savings. She wants to know the longest sequence of days
where her total savings equal exactly K units. All amounts are positive.
Input format:-
First line: Two integers N and K
Second line: N space-separated positive integers
Output format:-
Length of the longest subarray summing to K
Test Case:
Input:
7 15
1237516
Output:
3
Explanation:
Subarray [3, 7, 5] sums to 15.
Algorithm:
1. Accept N, K and array.
2. Initialize pointers and sum.
3. Use sliding window to check sum.
4. Adjust start and end to maintain required sum.
5. Update max length when sum equals K.
6. Print max length.
Q14: Longest Subarray with Given Sum K (Including Negatives)
Problem Statement:-
Ravi tracks temperature changes including negative values. He wants to find the
longest continuous period (subarray) where the sum equals K.
Input format:-
First line: Two integers N and K
Second line: N space-separated integers (can include negatives)
Output format:-
Length of the longest subarray summing to K
Test Case:
Input:
8 7 10 5 2 7 1 9 -1 -1
Output:
4
Explanation:
Subarray [2, 7, 1, -3] adds up to 7.
Algorithm:
1. Accept input N, K and array.
2. Use hashmap to track prefix sum and first index.
3. Traverse array, keep cumulative sum.
4. If (sum - K) is in map, update max length.
5. Store sum in map if not already present.
6. Print max length.
Q15: Count Frequency of Each Element
Problem Statement:-
Nisha is preparing reports of survey data. She wants to know how many times
each answer was selected. Help her count frequencies.
Input format:-
First line: Integer N
Second line: N space-separated integers
Output format:-
Each unique number and its frequency
Test Case:
Input:
6
122312
Output:
1 -> 2
2 -> 3
3 -> 1
Explanation:
Element 1 appears twice, 2 appears thrice, 3 appears once.
Algorithm:
1. Accept N and array.
2. Initialize dictionary freq.
3. Traverse array:
o Increment count of element in dictionary.
4. Print each key and value.
Q16: Find Common Elements in Three Sorted Arrays
Problem Statement:-
An analyst is comparing customer lists from three different branches to find
customers who visited all three. Help him identify common elements across all
three sorted arrays.
Input format:-
First line: Three integers N1, N2, N3 (sizes of the three arrays)
Second line: N1 sorted integers
Third line: N2 sorted integers
Fourth line: N3 sorted integers
Output format:-
Space-separated integers common to all three arrays
Test Case:
Input:
658
1 5 10 20 40 80
6 7 20 80 100
3 4 15 20 30 70 80 120
Output:
20 80
Explanation:
Only 20 and 80 appear in all three arrays.
Algorithm:
1. Accept N1, N2, N3 and the arrays.
2. Initialize pointers i, j, k = 0.
3. Traverse all arrays using a while loop:
o If arr1[i] == arr2[j] == arr3[k], add to result and increment all
pointers.
o Else increment pointer(s) with the smallest value.
4. Print result.
Q17: Rotate Array to the Right by K Steps
Problem Statement:-
A data visualization tool needs to rotate graphs cyclically. Help implement a
function to rotate an array to the right by K steps.
Input format:-
First line: Two integers N and K
Second line: N space-separated integers
Output format:-
Array after rotating right by K steps
Test Case:
Input:
5212345
Output:
45123
Explanation:
Last 2 elements move to the front.
Algorithm:
1. Accept N, K, and array.
2. K = K % N to handle extra rotations.
3. Slice array as: last K elements + first N-K elements.
4. Print result.
Q18: Maximum Product Subarray
Problem Statement:-
A stock analyst is evaluating product values over days. Help find the contiguous
subarray (within the array) which has the largest product.
Input format:-
First line: Integer N
Second line: N space-separated integers
Output format:-
Maximum product of a subarray
Test Case:
Input:
5 2 3 -2 4 -1
Output:
48
Explanation:
Subarray [2, 3, -2, 4, -1] gives maximum product 48.
Algorithm:
1. Accept N and array.
2. Initialize max_prod, min_prod, result as first element.
3. Loop from index 1 to N-1:
o If current < 0, swap max and min.
o Update max_prod = max(current, max_prod*current)
o Update min_prod = min(current, min_prod*current)
o Update result = max(result, max_prod)
4. Print result.
Q19: Check if Two Arrays are Equal (With Frequency)
Problem Statement:-
A QA engineer compares expected and actual output arrays. Help check if both
arrays contain the same elements with the same frequency, regardless of order.
Input format:-
First line: Integer N
Second line: N space-separated integers (array A)
Third line: N space-separated integers (array B)
Output format:-
Print "Yes" if equal, else "No"
Test Case:
Input:
51234554321
Output:
Yes
Explanation:
Both arrays have same elements with same frequencies.
Algorithm:
1. Accept N and both arrays.
2. Create frequency dictionaries for both.
3. Compare both dictionaries.
4. Print "Yes" if equal, otherwise "No".
Q20: Find the Element that Appears Only Once When Others Appear Thrice
Problem Statement:-
A system logs error codes, but due to a bug, one error was logged only once
while others were logged exactly three times. Identify the unique error code.
Input format:-
First line: Integer N
Second line: N space-separated integers
Output format:-
The unique number
Test Case:
Input:
76133366
Output:
1
Explanation:
Every number appears thrice except 1.
Algorithm:
1. Accept N and array.
2. Initialize dictionary for frequency.
3. Count frequency of each number.
4. Return number with frequency 1.
MEDIUM
Q21: 2Sum Problem
Problem Statement:-
Asha is designing a game where two coins must sum to a given target value.
Help her identify if any two numbers in the array sum to the target.
Input format:-
First line: Two integers N and Target
Second line: N space-separated integers
Output format:-
Indices (0-based) of the two elements that sum up to Target (any valid
pair)
Test Case:
Input:
4 9 2 7 11 15
Output:
01
Explanation:
Elements at indices 0 and 1 (2 + 7 = 9) form the required sum.
Algorithm:
1. Accept N, Target and array.
2. Initialize a hashmap to store number and its index.
3. Loop through array:
o For each number, check if Target - num exists in hashmap.
o If yes, return indices.
o Else, store current number and index in hashmap.
Q22: Sort an Array of 0’s, 1’s and 2’s
Problem Statement:-
In a color categorization system, you need to arrange items labeled 0, 1, and 2 in
order. Help sort them efficiently without using in-built sorting.
Input format:-
First line: Integer N
Second line: N space-separated integers (0s, 1s, 2s only)
Output format:-
Sorted array
Test Case:
Input:
6021201
Output:
001122
Explanation:
The array is rearranged in increasing order.
Algorithm:
1. Accept N and array.
2. Use three pointers: low, mid, high.
3. Traverse using mid:
o If arr[mid]==0, swap with low, increment low and mid.
o If arr[mid]==1, move mid.
o If arr[mid]==2, swap with high, decrement high.
4. Print sorted array.
Q23: Majority Element (>n/2 times)
Problem Statement:-
In a voting system, one candidate may have more than half the total votes.
Identify this majority element if it exists.
Input format:-
First line: Integer N
Second line: N space-separated integers
Output format:-
The majority element or -1 if none exists
Test Case:
Input:
522123
Output:
2
Explanation:
Element 2 appears 3 times, more than half of 5.
Algorithm:
1. Accept N and array.
2. Use Boyer-Moore Voting Algorithm to find candidate.
3. Verify candidate count.
4. Print element if count > N/2, else -1.
Q24: Kadane’s Algorithm, Maximum Subarray Sum
Problem Statement:-
Ravi analyzes profit variations across days. Help him find the contiguous period
with the highest profit (maximum sum subarray).
Input format:-
First line: Integer N
Second line: N space-separated integers
Output format:-
Maximum subarray sum
Test Case:
Input:
9 -2 1 -3 4 -1 2 1 -5 4
Output:
6
Explanation:
Maximum sum is for subarray [4, -1, 2, 1].
Algorithm:
1. Accept N and array.
2. Initialize max_sum = current_sum = arr[0].
3. Loop from index 1:
o current_sum = max(arr[i], current_sum + arr[i])
o max_sum = max(max_sum, current_sum)
4. Print max_sum.
Q25: Print Subarray with Maximum Subarray Sum
Problem Statement:-
From the financial data, identify not just the maximum sum but the exact period
(subarray) which gives this sum.
Input format:-
First line: Integer N
Second line: N space-separated integers
Output format:-
The subarray that gives the maximum sum
Test Case:
Input:
9 -2 1 -3 4 -1 2 1 -5 4
Output:
4 -1 2 1
Explanation:
This subarray has the maximum sum of 6.
Algorithm:
1. Accept N and array.
2. Initialize variables: max_sum, current_sum, start, end, s.
3. Loop through array:
o Update current_sum
o If current_sum>max_sum, update max_sum and track start/end.
o If current_sum< 0, reset current_sum and s.
4. Print subarray from start to end.
Q26: Stock Buy and Sell
Problem Statement:-
An investor is tracking stock prices over several days. Help them find the best
day to buy and the best day to sell to maximize profit.
Input format:-
First line: Integer N
Second line: N space-separated integers (stock prices)
Output format:-
Maximum profit
Test Case:
Input:
6715364
Output:
5
Explanation:
Buy on day 2 (price=1), sell on day 5 (price=6), profit = 6 - 1 = 5.
Algorithm:
1. Accept N and stock prices.
2. Initialize min_price = infinity, max_profit = 0.
3. Traverse array:
o Update min_price to current if smaller.
o Calculate profit = current - min_price.
o Update max_profit if profit is higher.
4. Print max_profit.
Q27: Rearrange Array in Alternating Positive and Negative Items
Problem Statement:-
Riya wants to rearrange a mixed array of numbers into an alternating sequence
of positive and negative values, starting with positive.
Input format:-
First line: Integer N
Second line: N space-separated integers
Output format:-
Rearranged array in alternating format
Test Case:
Input:
6 -1 2 -3 4 -5 6
Output:
2 -1 4 -3 6 -5
Explanation:
Positive and negative elements are placed alternately.
Algorithm:
1. Accept N and array.
2. Separate positive and negative elements.
3. Interleave them alternatively.
4. Append remaining elements if any.
5. Print the result.
Q28: Next Permutation
Problem Statement:-
A coder wants to find the next lexicographically greater permutation of a number
sequence. Help compute the next permutation in-place.
Input format:-
First line: Integer N
Second line: N space-separated integers
Output format:-
Next permutation of the array
Test Case:
Input:
3123
Output:
132
Explanation:
Next greater permutation after [1, 2, 3] is [1, 3, 2].
Algorithm:
1. Find the rightmost index i where arr[i] <arr[i+1].
2. Find the rightmost element greater than arr[i].
3. Swap them.
4. Reverse the part after index i.
5. Print the result.
Q29: Leaders in an Array
Problem Statement:-
A leader is an element greater than all elements to its right. Help identify all
leaders in the array.
Input format:-
First line: Integer N
Second line: N space-separated integers
Output format:-
All leaders in the array
Test Case:
Input:
6 16 17 4 3 5 2
Output:
17 5 2
Explanation:
17 is greater than all to its right, 5 > 2, and 2 is last.
Algorithm:
1. Accept N and array.
2. Traverse array from right to left.
3. Keep track of max_so_far.
4. If current >max_so_far, add to leaders.
5. Print leaders in reverse order.
Q30: Longest Consecutive Sequence in an Array
Problem Statement:-
A sports analyst is looking for the longest sequence of consecutive days a player
scored. Find the longest consecutive sequence in an unsorted array.
Input format:-
First line: Integer N
Second line: N space-separated integers
Output format:-
Length of the longest consecutive sequence
Test Case:
Input:
7 100 4 200 1 3 2 5
Output:
5
Explanation:
Longest sequence is [1, 2, 3, 4, 5].
Algorithm:
1. Accept N and array.
2. Store all elements in a set.
3. For each element, check if it’s the start of a sequence.
4. Count the length by checking next consecutive numbers.
5. Update max_length and print it.
Q31: Set Matrix Zeros
Problem Statement:-
In a spreadsheet, when a cell has zero, its entire row and column should be set
to zero. Help implement this behavior on a 2D matrix.
Input format:-
First line: Two integers R and C (rows and columns)
Next R lines: C space-separated integers
Output format:-
The modified matrix after setting entire row and column to 0 for every cell
with 0
Test Case:
Input:
33111101111
Output:
101000101
Explanation:
The cell (1,1) is 0, so row 1 and column 1 are set to 0.
Algorithm:
1. Accept R and C, then read the matrix.
2. Create two sets: zero_rows and zero_cols.
3. First pass: store row/col indexes where 0 is found.
4. Second pass: update matrix elements at those row/col indices to 0.
5. Print modified matrix.
Q32: Rotate Matrix by 90 Degrees
Problem Statement:-
To display an image from a different angle, a 2D matrix (image) needs to be
rotated by 90 degrees clockwise.
Input format:-
First line: Integer N (NxN matrix)
Next N lines: N space-separated integers
Output format:-
Rotated matrix (each row in new line)
Test Case:
Input:
3123456789
Output:
741852963
Explanation:
Each row becomes a column in reverse.
Algorithm:
1. Accept N and the matrix.
2. Transpose the matrix.
3. Reverse each row.
4. Print the rotated matrix.
Q33: Print the Matrix in Spiral Manner
Problem Statement:-
To visually represent the unfolding of data, print a matrix in spiral order starting
from the top-left.
Input format:-
First line: Two integers R and C
Next R lines: C space-separated integers
Output format:-
Spiral order of elements (single line)
Test Case:
Input:
33123456789
Output:
123698745
Explanation:
Start from top-left and move inwards in spiral.
Algorithm:
1. Accept R, C and matrix.
2. Initialize top, bottom, left, right boundaries.
3. Loop and print elements in right, down, left, up direction.
4. Update boundaries accordingly.
5. Continue until all elements are printed.
Q34: Count Subarrays with Given Sum
Problem Statement:-
Given a list of daily transaction values, find how many continuous subarrays sum
up to a given value K.
Input format:-
First line: Two integers N and K
Second line: N space-separated integers
Output format:-
Count of subarrays summing to K
Test Case:
Input:
5512321
Output:
2
Explanation:
Subarrays [2,3] and [3,2] sum to 5.
Algorithm:
1. Accept N, K and array.
2. Initialize prefix sum and hashmap.
3. Traverse array to update prefix and check for prefix-K in map.
4. Update count accordingly.
5. Print the count.