Skip to content

Commit 705b312

Browse files
add 2537 hashmap approach
1 parent b9137d7 commit 705b312

File tree

2 files changed

+41
-2
lines changed

2 files changed

+41
-2
lines changed

contest/src/main/java/com/github/contest/Execute.kt

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
package com.github.contest
22

33

4-
import com.github.contest.hashTable.countGood
4+
import com.github.contest.hashTable.countGoodAlternativeSolution
55
import com.github.contest.math.numberOfPowerfulInt
66
import com.github.contest.strings.fullJustify
77
import com.github.contest.strings.subStrHash
@@ -14,7 +14,7 @@ import java.util.TreeMap
1414

1515
fun main() {
1616

17-
countGood(intArrayOf(3, 1, 4, 3, 2, 2, 4), 2).also { println(it) }
17+
countGoodAlternativeSolution(intArrayOf(3, 1, 4, 3, 2, 2, 4), 2).also { println(it) }
1818

1919
}
2020

contest/src/main/java/com/github/contest/hashTable/HashTableAlternativeSolution.kt

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -45,4 +45,43 @@ fun countBadPairsAltSolution(nums: IntArray): Long {
4545

4646
class Counter {
4747
var count: Int = 0
48+
}
49+
50+
/**
51+
* 2537. Count the Number of Good Subarrays
52+
* Alternative Solution Optimal
53+
* Hash Map Approach
54+
*/
55+
56+
fun countGoodAlternativeSolution(nums: IntArray, k: Int): Long {
57+
var left = 0
58+
var count = 0L
59+
var totalPairs = 0L
60+
val freq = mutableMapOf<Int, Int>()
61+
62+
for (right in nums.indices) {
63+
// Update the frequency of the current element
64+
val num = nums[right]
65+
val currentFreq = freq.getOrDefault(num, 0)
66+
// Each existing occurrence creates new pairs
67+
totalPairs += currentFreq
68+
freq[num] = currentFreq + 1
69+
70+
// While the window has enough pairs, try to shrink from the left
71+
while (totalPairs >= k) {
72+
val leftNum = nums[left]
73+
// Before removing, reduce the pairs count
74+
totalPairs -= freq[leftNum]!! - 1
75+
freq[leftNum] = freq[leftNum]!! - 1
76+
if (freq[leftNum] == 0) {
77+
freq.remove(leftNum)
78+
}
79+
left++
80+
}
81+
82+
// All subarrays ending at right with start <= left-1 are good
83+
count += left
84+
}
85+
86+
return count
4887
}

0 commit comments

Comments
 (0)