Skip to content

Commit 76b0b15

Browse files
authored
Merge pull request #42 from mrid88/feature/div
Solution - #2206 - Mridul/Edited - 23/03/2025
2 parents d28ad7a + 727f728 commit 76b0b15

File tree

2 files changed

+53
-0
lines changed

2 files changed

+53
-0
lines changed
Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
# Explanation of the Program
2+
3+
## **Objective**
4+
The program determines whether it is possible to divide an array of integers into pairs such that each pair consists of identical elements. If this is possible, it returns `true`; otherwise, it returns `false`.
5+
6+
---
7+
8+
## **Step-by-Step Explanation**
9+
10+
### **1. Input and HashMap Initialization**
11+
- The input is an array `nums` of integers.
12+
- A `HashMap` is used to count the frequency of each integer in the array.
13+
- **Key:** The integer from the array.
14+
- **Value:** The number of times the integer appears in the array.
15+
16+
### **2. Counting Frequencies**
17+
```java
18+
for (int i = 0; i < n; i++) {
19+
map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
20+
}
21+
22+
Time Complexity
23+
Building the Frequency Map:
24+
The loop iterates through the array once, making this O(n), where n is the length of the array.
25+
Checking Frequencies:
26+
The loop iterates through the values in the HashMap, which is proportional to the number of distinct integers in the array. In the worst case, there can be up to n distinct integers, so this step is O(n).
27+
Overall Time Complexity: O(n)
28+
29+
Space Complexity
30+
HashMap Storage:
31+
The HashMap stores the frequencies of at most n distinct integers. In the worst case, the space required is O(n).
32+
Overall Space Complexity: O(n)
Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
import java.util.HashMap;
2+
3+
class Solution {
4+
public boolean divideArray(int[] nums) {
5+
HashMap<Integer,Integer> map = new HashMap<>();
6+
7+
int n = nums.length;
8+
9+
for(int i = 0;i<n;i++){
10+
map.put(nums[i], map.getOrDefault(nums[i], 0) + 1);
11+
}
12+
13+
if(n%2!=0) return false;
14+
15+
for(int val:map.values()){
16+
if(val%2!=0) return false;
17+
}
18+
19+
return true;
20+
}
21+
}

0 commit comments

Comments
 (0)