0% found this document useful (0 votes)
14 views

Array Interview Questions Data Structure Algorithms 1730130847

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
14 views

Array Interview Questions Data Structure Algorithms 1730130847

Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 36

Data Structure

Algorithms
Array
Interview
Questions
Array Introduction

What is Array
Array is a linear data structure where all elements are
arranged sequentially. It is a collection of elements of
same data type stored at contiguous memory
locations.
Array Types

Types of Arrays
Arrays can be classified in two ways:
On the basis of Size
On the basis of Dimensions
Array Operations

1. Array Traversal
Array traversal involves visiting all the elements
of the array once.

2. Insertion in Array
We can insert one or multiple elements at any
position in the array.

3. Deletion in Array
We can delete an element at any index in an array.

4. Searching in Array
We can traverse over an array and search for an
element.
Array Operations Complexity Analysis

Time Complexity

Space Complexity
1. Two Sum
Problem Statement:
Given an array of integers nums and an integer target,
return the indices of the two numbers such that they
add up to the target.

Example
Input: nums = [2, 7, 11, 15], target = 9
Output: [0, 1]
Concepts Involved:
Hash Maps: To efficiently store elements and their indices,
enabling O(1) lookups.
Nested Loops (Brute Force): For beginners, using nested loops
to find pairs.
Approach:.
Brute Force (Nested Loops) - Check each pair of
elements to see if their sum equals the target. This
approach has O(n²) time complexity.
Hash Map Approach - Use a hash map (dictionary) to
store each element's index as we iterate through the
array. For each element, check if target -
current_element exists in the hash map. This gives us an
O(n) solution.
2. Validate Subsequence
Problem Statement:
Given two arrays array and sequence, check if the sequence is a
subsequence of array. A subsequence is derived by deleting
some or no elements from array without changing the order of
the remaining elements.

Example
Input: array = [5, 1, 22, 25, 6, -1, 8, 10], sequence = [1, 6, -1, 10]
Output: true

Concepts Involved:
Two Pointers: Iterating over two arrays to check if
one is a subsequence of the other.
Iteration: Simple comparison and iteration to match
the subsequence.
Approach:.
Use two pointers, one for array and one for
sequence.
Iterate through array and move the pointer in
sequence if there's a match.
If the pointer in sequence reaches the end, it
means sequence is a valid subsequence of array.
3. Reverse an Array
Problem Statement:
Given an array arr, reverse the elements of the array in-
place.

Example
Input: arr = [1, 2, 3, 4, 5]
Output: [5, 4, 3, 2, 1]

Concepts Involved:
Two Pointer Technique: Swap elements from the
start and end moving towards the center.
In-place Modification: Modify the array without using
extra space.
Approach:.
Use two pointers, one at the beginning and one at
the end.
Swap the elements at these pointers and move
them towards each other.
Continue swapping until the two pointers meet.
4. Check if Array is Sorted
Problem Statement:
Given an array arr, determine if the array is sorted in
non-decreasing order.

Example
Input: arr = [1, 2, 3, 4, 5]
Output: true

Concepts Involved:
Linear Scan: Simple loop to check for non-decreasing
order.

Approach:.
Iterate through the array and check if each
element is less than or equal to the next.
If any element is greater than the next, the array is
not sorted.
5. Remove Duplicates from Array
Problem Statement:
Given a sorted array nums, remove the duplicates in-
place such that each unique element appears only once.

Example
Input: nums = [0, 1, 1, 2, 2, 3, 4, 4]
Output: 5, nums = [0, 1, 2, 3, 4, _, _, _]

Concepts Involved:
Two Pointer Technique: One pointer iterates over
the array, the other marks the position of the next
unique element.

Approach:.
Use two pointers, i and j.
Pointer j iterates through the array, while i only
moves when a unique element is found.
Overwrite duplicates with unique elements as they
are found, resulting in an array of unique elements
at the beginning.
6. Second Largest Element Array
Problem Statement:
Given an array of integers arr, find the second largest
unique element in the array.

Example
Input: arr = [10, 20, 4, 6, 7]
Output: 10

Concepts Involved:
Linear Scan: One-pass or two-pass scan through the
array to find the two largest unique elements.
Approach:.
Single Pass Approach - Keep track of two variables:
first (largest) and second (second largest). Iterate
through the array once and update these variables
based on the conditions.
Sorting Approach - Sort the array in descending
order and return the second unique element. This
approach has O(n log n) complexity due to sorting,
but it's straightforward.
7. Move Element To End
Problem Statement:
Given an array arr and an integer toMove, move all
occurrences of toMove to the end of the array in-place.

Example
Input: arr = [2, 1, 2, 2, 3, 4, 2], toMove = 2
Output: [4, 1, 3, 2, 2, 2, 2]

Concepts Involved:
Two-Pointer Technique: Use one pointer at the start
and another at the end to swap elements.
Approach:.
Use two pointers: one (left) at the start and the
other (right) at the end.
If arr[left] equals toMove, swap it with arr[right]
and decrement right.
If arr[left] is not toMove, increment left.
Continue until left meets right.
8. Find Missing Number Array
Problem Statement:
Given an array nums containing n distinct numbers in
the range [0, n], return the only number in the range
that is missing from the array.

Example
Input: nums = [3, 0, 1]
Output: 2

Concepts Involved:
Arithmetic Sum: Use the sum of the first n natural
numbers.
XOR Trick: XOR all elements with numbers from 0 to
n.
Approach:.
Arithmetic Sum: Sum of numbers from 0 to n is n
* (n + 1) / 2. Subtract the sum of elements in nums
from this sum to get the missing number.
XOR Approach: XOR all elements in nums with
numbers from 0 to n. The duplicate elements will
cancel out, leaving the missing number.
9. Majority Element
Problem Statement:
Given an array nums of size n, return the majority
element. The majority element is the element that
appears more than n / 2 times.

Example
Input: nums = [3, 2, 3]
Output: 3

Concepts Involved:
Boyer-Moore Voting Algorithm: A linear-time
algorithm to find the majority element.
Hash Map: Use a hash map to count occurrences.
Approach:.
Boyer-Moore Voting Algorithm: Maintain a
candidate and a count. Traverse the array,
incrementing count for the candidate when the
current element matches it, and decrementing
when it does not. If the count reaches zero,
choose a new candidate.
Hash Map: Count occurrences of each element
and return the element with count greater than n
/ 2.
10. Reverse Vowels of a String
Problem Statement:
Given a string s, reverse only the vowels of the string
and return it. The vowels are 'a', 'e', 'i', 'o', and 'u', and
they can appear in both lower and uppercase forms.

Example
Input: s = "hello"
Output: "holle"

Concepts Involved:
Two Pointer Technique: Use two pointers to find
vowels from both ends and swap them.

Approach:.
Initialize two pointers, left at the start and right at
the end of the string.
Move left forward until it finds a vowel.
Move right backward until it finds a vowel.
Swap the vowels at left and right and continue
until the pointers meet.
11. Array of Products
Problem Statement:
Given an array arr of integers, return a new array
products such that each element at index i of products
is the product of all the numbers in arr except arr[i].

Example
Input: arr = [1, 2, 3, 4]
Output: [24, 12, 8, 6]

Concepts Involved:
Prefix Product Array: An array storing cumulative
products from the left.
Suffix Product Array: An array storing cumulative
products from the right.
Approach:.
First, create a prefix array where prefix[i] is the
product of all elements to the left of i.
Create a suffix array where suffix[i] is the product
of all elements to the right of i.
For the result at i, multiply prefix[i] and suffix[i].
12. Merge Two Sorted Arrays
Problem Statement:
Given two sorted arrays arr1 and arr2, merge them into a
single sorted array.

Example
Input: arr1 = [1, 3, 5], arr2 = [2, 4, 6]
Output: [1, 2, 3, 4, 5, 6]

Concepts Involved:
Two-pointer technique: Merging sorted arrays by
iterating with two pointers.

Approach:.
Initialize two pointers, one for each array.
Compare the elements at each pointer and add
the smaller element to the result array.
Move the pointer of the array from which the
element was taken.
If one array is exhausted, add the remaining
elements of the other array.
13. Find the Intersection of Arrays
Problem Statement:
Given two arrays arr1 and arr2, return an array that
represents their intersection. Each element in the result
must be unique.

Example
Input: arr1 = [1, 2, 2, 1], arr2 = [2, 2]
Output: [2]

Concepts Involved:
Hash Map: Use a hash set to store elements and
check for duplicates.
Sorting and Two-Pointer Technique: Sort both
arrays and use two pointers to find common
elements.
Approach:.
Hash Set: Store all elements of arr1 in a set. Then,
for each element in arr2, check if it exists in the
set.
Two Pointers on Sorted Arrays: Sort both arrays
and use two pointers to find common elements
without duplicates.
14. Zero Sum Subarray
Problem Statement:
Given an array arr, find if there exists a subarray with a
sum equal to zero.

Example
Input: arr = [1, 2, -3, 4, 5]
Output: true
Explanation: Subarray [1, 2, -3] has a sum of 0.

Concepts Involved:
Prefix Sum with Hash Map: Store cumulative sums
and check for repeats.
Approach:.
Use a prefix sum and a hash map.
For each element, calculate the cumulative sum up
to that index.
If this cumulative sum has been seen before, a
subarray with zero sum exists.
15. Best Time to Buy and Sell Stock
Problem Statement:
You are given an array prices where prices[i] represents
the stock price on day i. Find the maximum profit you
can achieve from a single buy and sell.

Example
Input: prices = [7, 1, 5, 3, 6, 4]
Output: 5

Concepts Involved:
Single Pass with Minimum Tracking: Track the
minimum price and the maximum profit achievable.

Approach:.
Traverse the array, keeping track of the minimum
price seen so far.
For each price, calculate the profit if sold on that
day, and update the maximum profit if it’s higher.
16. Monotonic Array
Problem Statement:
An array is monotonic if it is either entirely non-
increasing or entirely non-decreasing. Given an array,
return true if the array is monotonic, or false otherwise.

Example
Input: arr = [1, 2, 2, 3] Output: true
Input: arr = [6, 5, 4, 4] Output: true

Concepts Involved:
Monotonic Condition Check: Check whether the
array is non-increasing or non-decreasing.
Approach:.
Initialize two boolean flags, isNonDecreasing and
isNonIncreasing.
Traverse the array once and compare each
adjacent pair of elements:
If arr[i] > arr[i + 1], set isNonDecreasing to false.
If arr[i] < arr[i + 1], set isNonIncreasing to false.
After traversing the array, if either
isNonDecreasing or isNonIncreasing is true, the
array is monotonic.
17. K-th Largest Element Array
Problem Statement:
Given an integer array nums and an integer k, return the
k-th largest element in the array.

Example
Input: nums = [3, 2, 1, 5, 6, 4], k = 2
Output: 5

Concepts Involved:
Min-Heap for efficient k-th largest element extraction.
Approach:.
Use a min-heap of size k to keep track of the
largest k elements.
Traverse the array, pushing each element to the
heap.
If the heap size exceeds k, remove the smallest
element.
The root of the heap will be the k-th largest
element.
18. Three Sum Closest
Problem Statement:
Given an integer array nums of n integers and an integer
target, find three integers in nums such that the sum is
closest to target.

Example
Input: nums = [-1, 2, 1, -4], target = 1
Output: 2

Concepts Involved:
Sorting the array to enable efficient two-pointer
traversal.
Two-Pointer Technique after fixing one element.

Approach:.
Sort the array to use two pointers.
Iterate over the array and fix one element at a
time.
Use two pointers to find two other elements such
that the sum of the three elements is as close as
possible to the target.
Update the closest sum if the current sum is closer
to the target.
19. Merge Overlapping Intervals
Problem Statement:
Given a collection of intervals, merge all overlapping
intervals.

Example
Input: intervals = [[1,3], [2,6], [8,10], [15,18]]
Output: [[1,6], [8,10], [15,18]]

Concepts Involved:
Sorting by the starting times.
Merging intervals based on overlap conditions.
Approach:.
Sort the intervals based on the start time.
Traverse through the sorted intervals and merge
any overlapping intervals by updating the end
time.
Use a list to store the merged intervals.
20. Minimum Number Platforms Required
Problem Statement:
Given arrival and departure times of trains at a railway
station, find the minimum number of platforms required
so that no train waits.

Example
Input: arrival = [900, 940, 950, 1100, 1500, 1800], departure
= [910, 1200, 1120, 1130, 1900, 2000]
Output: 3

Concepts Involved:
Sorting both arrival and departure times.
Two-pointer Technique to count overlapping intervals.

Approach:.
Sort both arrival and departure arrays.
Use two pointers, one for arrival and one for departure.
Traverse through the arrays; if arrival[i] is less than
departure[j], increment platform count and move to the
next arrival.
If arrival[i] is greater than or equal to departure[j],
decrement platform count and move to the next
departure.
Keep track of the maximum platform count.
21. Trapping Rain Water
Problem Statement:
Given an array height representing the elevation map
where the width of each bar is 1, compute how much
water it can trap after raining.

Example
Input: height = [0,1,0,2,1,0,1,3,2,1,2,1]
Output: 6

Concepts Involved:
Two-Pointer Approach to calculate trapped water.
Prefix and Suffix Max Arrays to keep track of
maximum heights on each side.

Approach:.
Use two pointers (left and right) to traverse the
array from both ends.
Keep track of the maximum height on both sides
and calculate trapped water based on the lower
max.
Alternatively, use prefix and suffix arrays to
precompute max heights and calculate water at
each position.
22. Median of Two Sorted Arrays
Problem Statement:
Given two sorted arrays nums1 and nums2 of size m and
n, return the median of the two sorted arrays.

Example
Input: nums1 = [1, 3], nums2 = [2]
Output: 2.0

Concepts Involved:
Binary Search on the smaller array.
Partitioning to balance the halves of two sorted
arrays.
Approach:.
Use binary search on the smaller array to find the
correct partition that divides the arrays into two
equal halves.
Calculate the median based on the elements
around the partition.
23. Sliding Window Maximum
Problem Statement:
Given an array nums and an integer k, find the maximum
for each sliding window of size k.

Example
Input: nums = [1,3,-1,-3,5,3,6,7], k = 3
Output: [3,3,5,5,6,7]

Concepts Involved:
Deque to store indices of elements in the current
window.
Maintaining elements in a Monotonic Decreasing Order
in the deque.
Approach:.
Use a deque to store indices of useful elements
for each window.
For each element, remove indices from the deque
that are outside the current window or are smaller
than the current element.
The front of the deque holds the maximum
element for the current window.
24. Chocolate Distribution Problem
Problem Statement:
Given an array of n integers nums where each element
represents the number of chocolates in a packet, and an
integer m which represents the number of students.
Distribute m packets such that the difference between
the maximum and minimum number of chocolates in
these packets is minimized.

Example
Input: nums = [7, 3, 2, 4, 9, 12, 56], m = 3
Output: 2

Concepts Involved:
Sorting the array to simplify finding minimum differences.
Sliding Window to select subarrays of size m.
Approach:.
Sort the array.
Use a sliding window of size m to find the subarray
with the minimum difference between the maximum
and minimum elements.
Return this minimum difference.
25. Find the Largest Range
Problem Statement:
Given an unsorted array of integers, find the length of
the largest range of consecutive integers in the array.
Concepts Involved:
Hash Map (Set): Use a hash set to keep track of
elements we’ve seen so we can easily check for the
existence of consecutive numbers.
Range Expansion: For each number, expand to find
the start and end of the range by checking
consecutive numbers in the set.

Approach:.
Store all numbers in a hash set for quick lookup.
Iterate through each number in the array. For each
number, if it's the start of a potential range (i.e.,
num - 1 is not in the set), expand the range.
Expand the range in both directions (upwards and
downwards) until you find numbers that are no
longer consecutive.
Track the maximum range found.
26. Calendar Matching
Problem Statement:
Given two people's calendar events and their working
hours, find available time slots where both people are
free and the duration is at least minDuration.

Concepts Involved:
Interval Merging to find common free times.
Time Conversion to handle times in a comparable
format.

Approach:.
Convert all time slots to minutes for easy
calculation.
Merge overlapping intervals from both people's
calendars.
Find gaps between merged intervals that are at
least minDuration long.
Convert available time slots back to HH format.
27. Sort Colors
Problem Statement:
Given an array nums with n objects colored red, white,
or blue, sort them in-place so that objects of the same
color are adjacent, with the colors in the order red,
white, and blue.

Example
Input: nums = [2,0,2,1,1,0]
Output: [0,0,1,1,2,2]

Concepts Involved:
Dutch National Flag Problem by Edsger Dijkstra.
Three-Way Partitioning to segregate three groups in
one pass.
Approach:.
Use three pointers: low (to track 0s), mid (current
index), and high (to track 2s).
Traverse through the array, moving 0s to the front
and 2s to the end in a single pass.
Increment or decrement the pointers based on the
value at mid.
28. Subarray Sum Divisible by K
Problem Statement:
Given an array of integers nums and an integer k, return
the number of (contiguous) subarrays that have a sum
divisible by k.

Example
Input: nums = [4,5,0,-2,-3,1], k = 5
Output: 7

Concepts Involved:
Prefix Sum with Modulo Operation to check
divisibility.
Using a Hash Map to store frequency of each
remainder.
Approach:.
Calculate the prefix sum modulo k.
If two prefix sums have the same remainder, the
subarray between them is divisible by k.
Use a hash map to track occurrences of each
remainder.
29. Longest Subarray With Sum
Problem Statement:
Given an array nums and a target sum, find the length of
the longest subarray whose sum equals the target.

Example
Input: nums = [1, -1, 5, -2, 3], target = 3
Output: 4

Concepts Involved:
Prefix Sum to keep track of cumulative sums.
Hash Map to store the earliest occurrence of each
prefix sum.

Approach:.
Calculate the prefix sum as you iterate through
the array.
For each prefix sum, check if prefixSum - target
exists in the hash map to find a subarray that
sums to target.
Store the first occurrence of each prefix sum in
the hash map.
30. Contiguous Array
Problem Statement:
Given a binary array, find the maximum length of a
contiguous subarray with an equal number of 0s and 1s.

Example
Input: nums = [0,1,0]
Output: 2

Concepts Involved:
Prefix Sum with Hash Map for tracking balance
between 0s and 1s.
Mapping 0 as -1 to make prefix sum zero when counts
of 0s and 1s are equal.
Approach:.
Map 0 to -1 so that we can treat the problem as
finding a subarray with a sum of zero.
Track prefix sums using a hash map, storing the
first occurrence of each sum.
If the same prefix sum appears again, it means
there's a subarray with equal 0s and 1s.

You might also like