Arrays
What is Array
What is an Array?
An array is a data structure that stores multiple elements of the same
data type in a contiguous memory location. It allows easy access to
elements using an index.
Uses of Arrays
1) Storing Multiple Values
2) Efficient Data Access(index)
3) Iteration
4) Sorting (Quick Sort, Merge Sort) and Searching(Binary Search)
5) Matrix Representation(2D arrays)
6) Memory Management
7) Used in Data Structures
How Arrays Manage Memory Efficiently?
1) Contiguous Memory Allocation
Arrays store elements in adjacent memory locations, making it easy to
access elements using index calculations.
Address of arr[i]=Base Address+(i×Size of data type)
O(1) time complexity
How Arrays Manage Memory Efficiently?
2) Fixed Memory Allocation (Static Arrays)
When an array is declared, a fixed block of memory is reserved at compile
time.
Example
int [] arr = new int[5];
Memory is allocated sequentially in the stack (for small arrays) or heap (for
dynamically allocated arrays).
How Arrays Manage Memory Efficiently?
2) Dynamic Memory Allocation (Resizable Arrays)
If the size of the array is unknown beforehand, dynamic allocation (heap memory) is used.
Java Example (Using ArrayList)
3) Memory Overhead and Garbage Collection
In Java, arrays allocated on the heap are automatically managed by the Garbage Collector (GC).
Unused arrays get deallocated to free up memory.
However, large unused arrays can still waste memory if not explicitly set to null.
Example:
int[] arr = new int[1000];
arr = null;
Why is an Array Used?
1) Fast Access
2) Memory Efficiency
3) Better Organization
4) Useful in Algorithm Implementation
Types of Arrays
One-Dimensional Array (1D Array)
A linear collection of elements stored in a single row.
Accessed using a single index.
Example:-
int arr[5] = {10, 20, 30, 40, 50};
cout << arr[2];// 30
Types of Arrays
Two-Dimensional Array (2D Array)
Stores data in rows and columns (like a matrix).
Accessed using two indices (row, column).
Example:-
0 1
int matrix[2][2] = {{1, 2}, {3, 4}};
[Link](matrix[1][1]);
Types of Arrays
Multi-Dimensional Array (nD Array)
Arrays with more than two dimensions, like 3D, 4D, etc.
Used in image processing, 3D gaming, and
scientific computing.
Example:-
arr = [[[1, 2], [3, 4]], [[5, 6], [7, 8]]]
[Link](arr[1][0][1]);
Questions
1) Sum of Array Elements
Given an array arr of size n, the task is to
find the sum of all the elements in the
array.
Examples:
Input: n=5, arr = [1,2,3,4,5]
Output: 15
2) Given an array of n elements. The task is to return the count of the number of odd numbers
in the array.
Examples:
Input: n=5, array = [1,2,3,4,5] Output: 3
3) Given an array nums of n integers, return reverse of the array.
Examples:
Input : nums = [1, 2, 3, 4, 5] Output : [5, 4, 3, 2, 1]
4) Given an array arr of n elements. The task is to reverse the
given array. The reversal of array should
be inplace. Examples:Input: n=5, arr = [1,2,3,4,5]
Output: [5,4,3,2,1]
Explanation: The reverse of the array [1,2,3,4,5] is [5,4,3,2,1]
Questions
5) Check if the Array is Sorted I
int[] arr = [20, 21, 45, 89, 89, 90]
Given an array arr of size n, the task is to check if the given array is
sorted in (ascending / Increasing / Non-decreasing) order.
If the array is sorted then return True, else return False.
6) Given an array of integers nums and an integer target, find the
smallest index (0 based indexing) where the target appears in the array.
If the target is not found in the array, return -1.
int nums[] = [2, 3, 4, 5, 3], target = 3
7)Find the Largest element in an array. Given an array, we have to find the largest
element in the array.
arr[] = {2,5,1,3,0}; Now Find Second Smallest and Second Largest Element in an array.
[1,2,4,7,7,5]. What about finding third smallest and third largest element in an array.
What's Integer.MIN_VALUE?
It's a constant in Java that holds the smallest value an int can store, which is
-2,147,483,648.
Why and When to Use Integer.MIN_VALUE?
You use it when:
You don’t want to rely on the first element of the array.
You want to write a more generic solution that works even if the array has
negative numbers only.
Integer.MAX_VALUE is 2,147,483,647
Test Cases
1. If the array has a mixture of positive and negative numbers:
int[] arr = {-10, 23, -5, 99, -1, 0};
// Approach1
int max = arr[0];
// Approach2
int max = Integer.MIN_VALUE;
The largest element is for both approaches: 99?
Test Cases
2. If all numbers are duplicates of one number:
int[] arr = {7, 7, 7, 7, 7};
// Approach1
int max = arr[0];
// Approach2
int max = Integer.MIN_VALUE;
The largest element is for both approaches: 7?
Test Cases
3. What if all numbers are negative duplicates?
int[] arr = {-3, -3, -3, -3};
// Approach1
int max = arr[0];
// Approach2
int max = Integer.MIN_VALUE;
The largest element is for both approaches: -3 ?
Test Cases
4. But if the array is empty?
if ([Link] == 0) {
[Link]("Array is empty.");
return;
int[] arr = {};
int max = arr[0]; what will be the answer when I do [Link](max); Array Index out of Bounds
How to x it?
5. Array with One Element
int[] arr = {42}; max value is 42
6. Array with Duplicates of the Max Element
int[] arr = {4, 7, 7, 2, 7};
✅ Output: 7
7. Array Contains Only Zero
int[] arr = {0, 0, 0, 0};
✅ Output: 0
fi
Test Cases
8. How do we get the last element in an array?
First element: arr[0]
Second element: arr[1]
...
Last element: arr[[Link]-1]
What is [Link]() in Java?
Where is it from?
It comes from the [Link].*.
So you must import it:
import [Link].*;
Test Cases
Sorting Array in Descending Order
📌 For primitive arrays like int[], Java doesn't support direct descending
sort using [Link]().
So, you have 2 options:
✅ Option 1: Use Integer[] instead of int[] + [Link]() with
Comparator
Integer[] arr = {5, 1, 9, 3, 7};
[Link](arr, [Link]());
[Link]("Descending sorted array: " + [Link](arr));
Test Cases
Why Integer[] and not int[]?
[Link]() works only on objects.
int[] is a primitive, but Integer[] is an object wrapper.
Option 2: Sort ascending and reverse manually (for int[]) using
temp variable and traversing till n/2
Questions
8) Left Rotate Array by One.
Given an integer array nums, rotate the array
to the left by one.
Note: There is no need to return anything,
just modify the given array.
Examples:Input: nums = [1, 2, 3, 4, 5] Output: [2, 3, 4, 5, 1]
Explanation: Initially, nums = [1, 2, 3, 4, 5]
Rotating once to left -> nums = [2, 3, 4, 5, 1]
Now Given an integer array nums and a non-negative
integer k, rotate the array to the left by k steps. Do dry run
Examples: Input: nums = [1, 2, 3, 4, 5, 6], k = 2
Output: nums = [3, 4, 5, 6, 1, 2]
Explanation: rotate 1 step to the left: [2, 3, 4, 5, 6, 1]
rotate 2 steps to the left: [3, 4, 5, 6, 1, 2]
9) Given an integer array nums, rotate the
array to the right by k steps, where k is
non-negative. Input: nums = [1,2,3,4,5,6,7], k = 3 Output: [5,6,7,1,2,3,4]
Test Cases
Left Rotate by 1 Position
What is the role of temp in the code?
What happens if we remove the last line nums[n-1] = temp;?
Can you modify this code to use a while loop instead of a for loop?
Right Rotate by 1 Position
How would you rotate the array to the right by 1 position?
Why does the loop go from n-2 to 0?
What happens if you forget to assign temp to nums[0]?
🤔 What happens when k = 0 or k = [Link]?
💥 What if the array is empty or has one element?
Test Cases
Left Rotate by K Positions
How can you rotate the array to the left by k positions?
Steps
1. Store first k elements
2. Shift the rest to the front
3. Copy temp elements to end
🤔 What happens when k = 0 or k = [Link]?
💥 What if the array is empty or has one element?
Test Cases
Can you now convert this logic to rotate right by k positions?
How would you do this in-place without extra space?
What is the purpose of k = k % n?
4) Right Rotate by K Positions
// 1⃣ Reverse function to be filled
public static void reverse(int[] arr, int start, int end) {
while (__________) {
int temp = arr[start];
arr[start] = arr[end];
arr[end] = temp;
__________;
__________;
}
}
2⃣ Rotate k elements to the left
public static void rotateLeftByK(int[] arr, int n, int k) {
k = k % n; // Handle k > n
// Step 1: Reverse first k elements
reverse(arr, 0, __________);
// Step 2: Reverse the rest
reverse(arr, __________, n - 1);
// Step 3: Reverse entire array
reverse(arr, 0, __________);
What happens when k = 0, k = n, or k > n?
k = 0: No change.
k = n: No change (full rotation = same array).
k > n: Same as k % n, because rotations cycle every n steps.
Can you rotate an array without using extra space? How?
Yes, using the reversal algorithm: reverse parts of the array in-place.
Can rotation be undone? How would you reverse a rotation?
Yes. Left rotation by k can be undone by right rotation by k, and vice versa.
Questions
10) Move Zeroes - [Link]
11) Remove duplicates from sorted array
Given an integer array nums sorted in non-decreasing order,
remove all duplicates in-place so that each unique element
appears only once. Return the number of unique elements in the
array. If the number of unique elements be k, then,Change the array
nums such that the first k elements of nums contain the unique
values in the order that they were present originally. The
remaining elements, as well as the size of the array does not matter
in terms of correctness. An array sorted in non-decreasing order is an array where every
element to the right of an element is either equal to or greater in value than that element.
Examples: Input: nums = [0, 0, 3, 3, 5, 6] Output: 4
Explanation: Resulting array = [0, 3, 5, 6, _, _] There are 4 distinct elements in nums and
the elements marked as _ can have any value.
"Try solving it using two pointers: one for tracking the position of the unique element, another for traversal.”
What if the array is empty? What should be returned?
int i = 0;
for (int j = ?; j < [Link]; j++) {
// Fill in the condition to check if nums[j] is a unique element
if (/* ??? */) {
??
??
}
}
return i + 1;
Vary the Initial Conditions
“Suppose the array has all identical elements like [7, 7, 7, 7]. What
should the returned value be? What will the array look like after
modification?”
Questions
12) Union of two sorted arrays
Given two sorted arrays nums1 and nums2, return an array that contains
the union of these two arrays. The
elements in the union must be in ascending order.
The union of two arrays is an array where all values are distinct and are present
in either the first array, the second
array, or [Link]:
Input: nums1 = [1, 2, 3, 4, 5], nums2 = [1, 2, 7]
Output: [1, 2, 3, 4, 5, 7]
Explanation: The elements 1, 2 are common to both, 3, 4, 5 are from nums1 and 7 is
from nums2
Input: nums1 = [3, 4, 6, 7, 9, 9], nums2 = [1, 5, 7, 8, 8]
Output: [1, 3, 4, 5, 6, 7, 8, 9]
Explanation: The element 7 is common to both, 3, 4, 6, 9 are from nums1 and 1, 5, 8 is from
numbs
arr1= [1,1,2,3,4,5]
arr2 =[2,3,4,4,5,6]
Union[] = [1,2,3,4,5,6]
Now do Intersection of 2 Sorted Arrays
arr1= [1,1,2,3,4,5]
arr2 =[2,3,4,4,5,6]
Questions
13) Given an array, and an element num the task is to find if num is present in the given array or not.
If present print the index of the element or print -1. Examples:
Example 1:
Input: arr[]= 1 2 3 4 5, num = 3. Output: 2
Explanation: 3 is present in the 2nd index
14) Given an integer N and an array of size N-1 containing N-1 numbers between 1 to N.
Find the number(between 1 to N), that is not present in the given array.
Examples
Example 1:
Input Format: N = 5, array[] = {1,2,4,5}
Result: 3
Explanation: In the given array, number 3 is missing. So, 3 is the answer.
Example 2:
Input Format: N = 3, array[] = {1,3}
Result: 2
Explanation: In the given array, number 2 is missing. So, 2 is the answer.
Input: nums = [2,2,1,1,1,2,2] Output: 2
15) [Link]
16) Check if Array Is Sorted and Rotated
[Link]
17) Two Sum : Check if a pair with given sum exists in Array. Given
an array of integers arr[] and an integer target.
1st variant: Return YES if there exist two numbers such that their sum
is equal to the target.
Otherwise, return NO.
2nd variant: Return indices of the two numbers such that their sum is
equal to the target. Otherwise,
we will return {-1, -1}.
Note: You are not allowed to use the same element twice. Example: If
the target is equal to 6 and
num[1] = 3, then nums[1] + nums[1] = target is not a solution.
Examples:
Example 1:
Input Format: N = 5, arr[] = {2,6,5,8,11}, target = 14
Result: YES (for 1st variant)
[1, 3] (for 2nd variant)
Explanation: arr[1] + arr[3] = 14. So, the answer is “YES” for the rst variant
and [1, 3] for 2nd variant.
fi
2 sum examples
1)arr = [5, 2, 6, 1], target = 7
2) arr = [3, 8, 5, 2, 1] target = 10
3) arr = [4, 6, 1, 2, 9] target = 20
4) arr = [10, 15, 3, 7] target = 17
5) Edge Case arr = [2, 4, 6] target = 20
Why not just return {i, j};?
Because Java requires arrays to be explicitly constructed using the new keyword when
you're creating them on-the-fly like this.
But when you're returning directly from a method, you must use new int[]{...}.
Questions
18) Majority Element
Given an array sums of size n, return the majority element.
The majority element is the element that appears more than
⌊n / 2⌋ times. You may assume that the majority element always
exists in the array.
Input: [3, 3, 4, 2, 3, 3, 3]
Example 1:
Input: nums = [3,2,3]
Output: 3
Example 2:
Input: nums = [2,2,1,1,1,2,2]
Output: 2
Questions
19) Given an integer array nums, find the subarray with the largest sum, and return its sum.
Example 1 [5, -2, 3, -1, 2, -4]
Example 2:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: The subarray [4,-1,2,1] has the largest sum 6.
Example 2:
Input: nums = [1]
Output: 1
Explanation: The subarray [1] has the largest sum 1.
Example 3:
Input: nums = [5,4,-1,7,8]
Output: 23
Explanation: The subarray [5,4,-1,7,8] has the largest sum 23.
Questions
20) Longest Subarray with given Sum K(Positives)(Homework)
Problem Statement: Given an array and a sum k, we need to print the
length of the longest subarray that sums to k.
Examples
Example 1:
Input Format: N = 3, k = 5, array[] = {2,3,5}
Result: 2
Explanation: The longest subarray with sum 5 is {2, 3}. And its length is 2.
Example 2:
Input Format: N = 5, k = 10, array[] = {2,3,5,1,9}
Result: 3
Explanation: The longest subarray with sum 10 is {2, 3, 5}. And its length is
3.
Questions
21) Longest Subarray with sum K | [Postives and Negatives](Homework)
Problem Statement: Given an array and a sum k, we need to
print the length of the longest subarray that sums to k.
Examples
Example 1:
Input Format: N = 3, k = 5, array[] = {2,3,5}
Result: 2
Explanation: The longest subarray with sum 5 is {2, 3}. And its
length is 2.
Example 2:
Input Format: N = 3, k = 1, array[] = {-1, 1, 1}
Result: 3
Explanation: The longest subarray with sum 1 is {-1, 1, 1}. And
its length is 3.
Questions
Index Number Needed to reach 100 Already Seen? Action
0 30 70 No Store 30
1 50 50 No Store 50
2 70 30 ✅ Yes Return (0, 2)
Questions
22)[Link]
23) [Link]
24) [Link]
25) [Link]
26) [Link]
or-equal-to-k-together/0
Questions
27) [Link]
28) [Link]
29) [Link]
30) [Link]
31) [Link]
32) [Link]
33) [Link]
Questions
34) [Link]
35) [Link]
36) [Link]
37) [Link]
38) [Link]
39) [Link]