From 4f9efb6b8b718086706ecb7078dbce6dc0ba6be0 Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Tue, 1 Apr 2025 09:20:20 +0100 Subject: [PATCH 01/30] add 2140 brute force solution --- .../main/java/com/github/contest/Execute.kt | 12 +++------- .../java/com/github/contest/dp/DpLeetcode.kt | 23 +++++++++++++++++++ 2 files changed, 26 insertions(+), 9 deletions(-) diff --git a/contest/src/main/java/com/github/contest/Execute.kt b/contest/src/main/java/com/github/contest/Execute.kt index 101ed5a5..cde6abd7 100644 --- a/contest/src/main/java/com/github/contest/Execute.kt +++ b/contest/src/main/java/com/github/contest/Execute.kt @@ -1,7 +1,7 @@ package com.github.contest -import com.github.contest.design.WordDictionary +import com.github.contest.dp.mostPoints import java.util.TreeMap @@ -11,15 +11,9 @@ import java.util.TreeMap fun main() { + val questions = arrayOf(intArrayOf(3, 2), intArrayOf(4, 3), intArrayOf(4, 4), intArrayOf(2, 5)) - val wordDictionary = WordDictionary() - wordDictionary.addWord("bad") - wordDictionary.addWord("dad") - wordDictionary.addWord("mad") - wordDictionary.search("pad").also { println(it) } // return False - wordDictionary.search("bad").also { println(it) } // return True - wordDictionary.search(".ad").also { println(it) } // return True - wordDictionary.search("b..").also { println(it) } + mostPoints(questions).also { println(it) } } fun generateTesting() { diff --git a/contest/src/main/java/com/github/contest/dp/DpLeetcode.kt b/contest/src/main/java/com/github/contest/dp/DpLeetcode.kt index e13fab9f..739cb757 100644 --- a/contest/src/main/java/com/github/contest/dp/DpLeetcode.kt +++ b/contest/src/main/java/com/github/contest/dp/DpLeetcode.kt @@ -541,6 +541,29 @@ fun longestSubsequence(arr: IntArray, difference: Int): Int { return maxLen } +/** + * 2140. Solving Questions With Brainpower + */ + +fun mostPoints(questions: Array): Long { + return solve(questions, 0) +} + +private fun solve(questions: Array, index: Int): Long { + if (index >= questions.size) { + return 0 + } + + val points = questions[index][0] + val brainpower = questions[index][1] + val take = points.toLong() + solve(questions, index + brainpower + 1) + + + val skip = solve(questions, index + 1) + + return maxOf(take, skip) +} + From 7def5769d94b499eff287a063ff9b9ede355dcc7 Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Tue, 1 Apr 2025 09:35:46 +0100 Subject: [PATCH 02/30] add 2140 two approach --- .../main/java/com/github/contest/Execute.kt | 4 ++-- .../java/com/github/contest/dp/DpLeetcode.kt | 18 ++++++++++++++++++ 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/contest/src/main/java/com/github/contest/Execute.kt b/contest/src/main/java/com/github/contest/Execute.kt index cde6abd7..26239484 100644 --- a/contest/src/main/java/com/github/contest/Execute.kt +++ b/contest/src/main/java/com/github/contest/Execute.kt @@ -1,7 +1,7 @@ package com.github.contest -import com.github.contest.dp.mostPoints +import com.github.contest.dp.mostPointsDp import java.util.TreeMap @@ -13,7 +13,7 @@ fun main() { val questions = arrayOf(intArrayOf(3, 2), intArrayOf(4, 3), intArrayOf(4, 4), intArrayOf(2, 5)) - mostPoints(questions).also { println(it) } + mostPointsDp(questions).also { println(it) } } fun generateTesting() { diff --git a/contest/src/main/java/com/github/contest/dp/DpLeetcode.kt b/contest/src/main/java/com/github/contest/dp/DpLeetcode.kt index 739cb757..75368cf4 100644 --- a/contest/src/main/java/com/github/contest/dp/DpLeetcode.kt +++ b/contest/src/main/java/com/github/contest/dp/DpLeetcode.kt @@ -564,6 +564,24 @@ private fun solve(questions: Array, index: Int): Long { return maxOf(take, skip) } +fun mostPointsDp(questions: Array): Long { + val n = questions.size + val dp = LongArray(n + 1) { 0L } + + for (i in n - 1 downTo 0) { + val points = questions[i][0] + val brainpower = questions[i][1] + val nextQuestion = i + brainpower + 1 + + val take = points.toLong() + (if (nextQuestion < n) dp[nextQuestion] else 0L) + val skip = dp[i + 1] + + dp[i] = maxOf(take, skip) + } + + return dp[0] +} + From f2b1a9791aeb12490f80885fa040cb847d945376 Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Tue, 1 Apr 2025 14:21:19 +0100 Subject: [PATCH 03/30] add 2467 --- .../main/java/com/github/contest/Execute.kt | 8 +- .../com/github/contest/graph/GraphLeetcode.kt | 86 ++++++++++++++++++- 2 files changed, 89 insertions(+), 5 deletions(-) diff --git a/contest/src/main/java/com/github/contest/Execute.kt b/contest/src/main/java/com/github/contest/Execute.kt index 26239484..e818730e 100644 --- a/contest/src/main/java/com/github/contest/Execute.kt +++ b/contest/src/main/java/com/github/contest/Execute.kt @@ -1,7 +1,7 @@ package com.github.contest -import com.github.contest.dp.mostPointsDp +import com.github.contest.graph.mostProfitablePath import java.util.TreeMap @@ -11,11 +11,11 @@ import java.util.TreeMap fun main() { - val questions = arrayOf(intArrayOf(3, 2), intArrayOf(4, 3), intArrayOf(4, 4), intArrayOf(2, 5)) - - mostPointsDp(questions).also { println(it) } + val edges = arrayOf(intArrayOf(0, 1), intArrayOf(1, 2), intArrayOf(1, 3), intArrayOf(3, 4)) + mostProfitablePath(edges, 3, intArrayOf(-2, 4, 2, -4, 6)).also { println(it) } } + fun generateTesting() { val sequence = sequenceOf(3, 5, 6, 7, 7, 8, 8, 8, 9, 3) sequence.map { it * 2 } diff --git a/contest/src/main/java/com/github/contest/graph/GraphLeetcode.kt b/contest/src/main/java/com/github/contest/graph/GraphLeetcode.kt index 4b541800..b8f05927 100644 --- a/contest/src/main/java/com/github/contest/graph/GraphLeetcode.kt +++ b/contest/src/main/java/com/github/contest/graph/GraphLeetcode.kt @@ -1,6 +1,9 @@ package com.github.contest.graph +import java.util.Arrays import java.util.LinkedList +import kotlin.math.max + /** * 997. Find the Town Judge @@ -64,4 +67,85 @@ fun findCenter(edges: Array): Int { a == c || a == d -> a else -> b } -} \ No newline at end of file +} + +/** + * 2467. Most Profitable Path in a Tree + */ + + +fun mostProfitablePath(edges: Array, bob: Int, amount: IntArray): Int { + val graph = Array(amount.size) { mutableListOf() } + for (edge in edges) { + graph[edge[0]].add(edge[1]) + graph[edge[1]].add(edge[0]) + } + + val bobPath = IntArray(amount.size) + Arrays.fill(bobPath, -1) + val path = ArrayList() + fillBobPath(bob, -1, path, graph) + + for (i in path.indices) { + bobPath[path[i]] = i + } + + return getAliceMaxScore(0, -1, 0, bobPath, graph, 0, amount) +} + +private fun fillBobPath( + node: Int, + parentNode: Int, + path: ArrayList, + graph: Array> +): Boolean { + if (node == 0) return true + for (neighborNode in graph[node]) { + if (neighborNode != parentNode) { + path.add(node) + if (fillBobPath(neighborNode, node, path, graph)) return true + path.removeAt(path.size - 1) + } + } + return false +} + +private fun getAliceMaxScore( + node: Int, + parentNode: Int, + currScore: Int, + bobPath: IntArray, + graph: Array>, + timestamp: Int, + amount: IntArray +): Int { + var currScore = currScore + if (bobPath[node] == -1 || bobPath[node] > timestamp) { + currScore += amount[node] + } else if (bobPath[node] == timestamp) { + currScore += amount[node] / 2 + } + if (graph[node].size == 1 && node != 0) return currScore + var maxScore = Int.MIN_VALUE + for (neighborNode in graph[node]) { + if (neighborNode != parentNode) { + maxScore = max( + maxScore.toDouble(), + getAliceMaxScore( + neighborNode, + node, + currScore, + bobPath, + graph, + timestamp + 1, + amount + ).toDouble() + ) + .toInt() + } + } + return maxScore +} + + + From 26801a3d6ae965c94d2ac23624426032ceee0860 Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Wed, 2 Apr 2025 10:12:51 +0100 Subject: [PATCH 04/30] add 2873 --- .idea/gradle.xml | 2 +- .idea/misc.xml | 2 +- .idea/other.xml | 549 ------------------ .../main/java/com/github/contest/Execute.kt | 14 +- .../com/github/contest/array/ArrayLeetcode.kt | 17 + 5 files changed, 31 insertions(+), 553 deletions(-) delete mode 100644 .idea/other.xml diff --git a/.idea/gradle.xml b/.idea/gradle.xml index bfe173f1..96ccfae7 100644 --- a/.idea/gradle.xml +++ b/.idea/gradle.xml @@ -4,6 +4,7 @@ diff --git a/.idea/misc.xml b/.idea/misc.xml index 0ad17cbd..9f71c83d 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -1,7 +1,7 @@ - + diff --git a/.idea/other.xml b/.idea/other.xml deleted file mode 100644 index 22069ff9..00000000 --- a/.idea/other.xml +++ /dev/null @@ -1,549 +0,0 @@ - - - - - - \ No newline at end of file diff --git a/contest/src/main/java/com/github/contest/Execute.kt b/contest/src/main/java/com/github/contest/Execute.kt index e818730e..4190f537 100644 --- a/contest/src/main/java/com/github/contest/Execute.kt +++ b/contest/src/main/java/com/github/contest/Execute.kt @@ -11,10 +11,20 @@ import java.util.TreeMap fun main() { - val edges = arrayOf(intArrayOf(0, 1), intArrayOf(1, 2), intArrayOf(1, 3), intArrayOf(3, 4)) - mostProfitablePath(edges, 3, intArrayOf(-2, 4, 2, -4, 6)).also { println(it) } +// val edges = arrayOf(intArrayOf(0, 1), intArrayOf(1, 2), intArrayOf(1, 3), intArrayOf(3, 4)) +// mostProfitablePath(edges, 3, intArrayOf(-2, 4, 2, -4, 6)).also { println(it) } +// + testing() + } +fun testing() { + val list = listOf(1, 2, 3) + list.reduceRight { i, acc -> + println("$i, $acc") + acc - i + }.also { println(it) } +} fun generateTesting() { val sequence = sequenceOf(3, 5, 6, 7, 7, 8, 8, 8, 9, 3) diff --git a/contest/src/main/java/com/github/contest/array/ArrayLeetcode.kt b/contest/src/main/java/com/github/contest/array/ArrayLeetcode.kt index 767dfb54..761e796b 100644 --- a/contest/src/main/java/com/github/contest/array/ArrayLeetcode.kt +++ b/contest/src/main/java/com/github/contest/array/ArrayLeetcode.kt @@ -140,6 +140,23 @@ fun mergeArrays(nums1: Array, nums2: Array): Array }.toTypedArray() } +/** + * 2873. Maximum Value of an Ordered Triplet I + */ + +fun maximumTripletValue(nums: IntArray): Long { + var max = 0L + for (i in nums.indices) { + for (j in i + 1 until nums.size) { + for (k in j + 1 until nums.size) { + max = maxOf(max, ((nums[i] - nums[j]).toLong() * nums[k].toLong())) + } + } + } + + return max +} + From 8aed66a8adb235ee17a7dd5cd72434b118ae5be6 Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Thu, 3 Apr 2025 17:13:05 +0100 Subject: [PATCH 05/30] add 2874 --- .../main/java/com/github/contest/Execute.kt | 18 +++++++-------- .../com/github/contest/array/ArrayLeetcode.kt | 22 ++++++++++++++++++- 2 files changed, 30 insertions(+), 10 deletions(-) diff --git a/contest/src/main/java/com/github/contest/Execute.kt b/contest/src/main/java/com/github/contest/Execute.kt index 4190f537..e5c46429 100644 --- a/contest/src/main/java/com/github/contest/Execute.kt +++ b/contest/src/main/java/com/github/contest/Execute.kt @@ -1,7 +1,9 @@ package com.github.contest -import com.github.contest.graph.mostProfitablePath +import com.github.contest.array.maximumTripletValue +import com.github.contest.array.maximumTripletValue + import java.util.TreeMap @@ -11,10 +13,11 @@ import java.util.TreeMap fun main() { -// val edges = arrayOf(intArrayOf(0, 1), intArrayOf(1, 2), intArrayOf(1, 3), intArrayOf(3, 4)) -// mostProfitablePath(edges, 3, intArrayOf(-2, 4, 2, -4, 6)).also { println(it) } -// - testing() + maximumTripletValue( + intArrayOf( + 15, 3, 3, 18, 19, 13, 7, 5, 18, 1, 8, 5 + ) + ).also { println(it) } } @@ -28,10 +31,7 @@ fun testing() { fun generateTesting() { val sequence = sequenceOf(3, 5, 6, 7, 7, 8, 8, 8, 9, 3) - sequence.map { it * 2 } - .filter { it > 3 } - .filter { it > 2 } - .constrainOnce() + sequence.map { it * 2 }.filter { it > 3 }.filter { it > 2 }.constrainOnce() } diff --git a/contest/src/main/java/com/github/contest/array/ArrayLeetcode.kt b/contest/src/main/java/com/github/contest/array/ArrayLeetcode.kt index 761e796b..ff335c50 100644 --- a/contest/src/main/java/com/github/contest/array/ArrayLeetcode.kt +++ b/contest/src/main/java/com/github/contest/array/ArrayLeetcode.kt @@ -1,5 +1,6 @@ package com.github.contest.array + /** * 1800. Maximum Ascending Subarray Sum */ @@ -144,7 +145,7 @@ fun mergeArrays(nums1: Array, nums2: Array): Array * 2873. Maximum Value of an Ordered Triplet I */ -fun maximumTripletValue(nums: IntArray): Long { +fun maximumTripletValueI(nums: IntArray): Long { var max = 0L for (i in nums.indices) { for (j in i + 1 until nums.size) { @@ -158,6 +159,25 @@ fun maximumTripletValue(nums: IntArray): Long { } +/** + * 2874. Maximum Value of an Ordered Triplet II + */ + + +fun maximumTripletValue(nums: IntArray): Long { + var maxi = Int.MIN_VALUE + var diff = 0 + var res = 0L + + for (i in nums.indices) { + maxi = maxOf(maxi, nums[i]) + if (i >= 2) res = maxOf(res, (diff.toLong() * nums[i])) + if (i >= 1) diff = maxOf(diff, (maxi - nums[i])) + } + + return res +} + From 31fd53aa30be88707c1f6a4048d172d77cc45227 Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Fri, 4 Apr 2025 19:32:47 +0100 Subject: [PATCH 06/30] add 848 --- .../main/java/com/github/contest/Execute.kt | 10 ++---- .../github/contest/strings/StringsLeetcode.kt | 33 +++++++++++++++++++ 2 files changed, 35 insertions(+), 8 deletions(-) diff --git a/contest/src/main/java/com/github/contest/Execute.kt b/contest/src/main/java/com/github/contest/Execute.kt index e5c46429..23b2a76a 100644 --- a/contest/src/main/java/com/github/contest/Execute.kt +++ b/contest/src/main/java/com/github/contest/Execute.kt @@ -1,8 +1,7 @@ package com.github.contest -import com.github.contest.array.maximumTripletValue -import com.github.contest.array.maximumTripletValue +import com.github.contest.strings.shiftingLetters import java.util.TreeMap @@ -13,12 +12,7 @@ import java.util.TreeMap fun main() { - maximumTripletValue( - intArrayOf( - 15, 3, 3, 18, 19, 13, 7, 5, 18, 1, 8, 5 - ) - ).also { println(it) } - + shiftingLetters("abc", intArrayOf(3, 5, 9)).also { println(it) } } fun testing() { diff --git a/contest/src/main/java/com/github/contest/strings/StringsLeetcode.kt b/contest/src/main/java/com/github/contest/strings/StringsLeetcode.kt index f9382ac4..bbba6e3a 100644 --- a/contest/src/main/java/com/github/contest/strings/StringsLeetcode.kt +++ b/contest/src/main/java/com/github/contest/strings/StringsLeetcode.kt @@ -1,2 +1,35 @@ package com.github.contest.strings +/** + * 848. Shifting Letters + */ + +fun shiftingLetters(str: String, shifts: IntArray): String { + val shifting = IntArray(shifts.size) + var sum = shifts.sum() + var res = "" + + for (i in shifting.indices) { + shifting[i] = sum + sum -= shifts[i] + } + + for (i in str.indices) { + val newCharValue = shiftLetter(str[i], shifting[i]) + res += newCharValue + + } + + return res +} + +private fun shiftLetter(char: Char, shift: Int): Char = when { + char in 'a'..'z' -> { + val base = 'a'.code + val offset = char.code - base + val shifted = (offset + shift) % 26 + (base + shifted).toChar() + } + else -> char +} + From 5ec47efc7da1b5e0313b1808d5dfcf43822ad6d3 Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Fri, 4 Apr 2025 20:06:00 +0100 Subject: [PATCH 07/30] add new file for strings and change last problem of strings --- .../main/java/com/github/contest/Execute.kt | 26 ++++++++++++++++++- .../strings/StringsAlternativeSolution.kt | 2 ++ .../github/contest/strings/StringsLeetcode.kt | 16 +++++++++--- .../contest/strings/StringsProdVariant.kt | 2 ++ 4 files changed, 41 insertions(+), 5 deletions(-) create mode 100644 contest/src/main/java/com/github/contest/strings/StringsAlternativeSolution.kt create mode 100644 contest/src/main/java/com/github/contest/strings/StringsProdVariant.kt diff --git a/contest/src/main/java/com/github/contest/Execute.kt b/contest/src/main/java/com/github/contest/Execute.kt index 23b2a76a..32d1f7b8 100644 --- a/contest/src/main/java/com/github/contest/Execute.kt +++ b/contest/src/main/java/com/github/contest/Execute.kt @@ -12,7 +12,31 @@ import java.util.TreeMap fun main() { - shiftingLetters("abc", intArrayOf(3, 5, 9)).also { println(it) } + shiftingLetters( + "mkgfzkkuxownxvfvxasy", + intArrayOf( + 505870226, + 437526072, + 266740649, + 224336793, + 532917782, + 311122363, + 567754492, + 595798950, + 81520022, + 684110326, + 137742843, + 275267355, + 856903962, + 148291585, + 919054234, + 467541837, + 622939912, + 116899933, + 983296461, + 536563513 + ) + ).also { println(it) } } fun testing() { diff --git a/contest/src/main/java/com/github/contest/strings/StringsAlternativeSolution.kt b/contest/src/main/java/com/github/contest/strings/StringsAlternativeSolution.kt new file mode 100644 index 00000000..f9382ac4 --- /dev/null +++ b/contest/src/main/java/com/github/contest/strings/StringsAlternativeSolution.kt @@ -0,0 +1,2 @@ +package com.github.contest.strings + diff --git a/contest/src/main/java/com/github/contest/strings/StringsLeetcode.kt b/contest/src/main/java/com/github/contest/strings/StringsLeetcode.kt index bbba6e3a..46c2e8c3 100644 --- a/contest/src/main/java/com/github/contest/strings/StringsLeetcode.kt +++ b/contest/src/main/java/com/github/contest/strings/StringsLeetcode.kt @@ -5,13 +5,18 @@ package com.github.contest.strings */ fun shiftingLetters(str: String, shifts: IntArray): String { - val shifting = IntArray(shifts.size) - var sum = shifts.sum() + val shifting = LongArray(shifts.size) + var sum = 0L var res = "" + for (element in shifts) { + val num = element.toLong() + sum += num + } + for (i in shifting.indices) { shifting[i] = sum - sum -= shifts[i] + sum -= shifts[i].toLong() } for (i in str.indices) { @@ -23,13 +28,16 @@ fun shiftingLetters(str: String, shifts: IntArray): String { return res } -private fun shiftLetter(char: Char, shift: Int): Char = when { +private fun shiftLetter(char: Char, shift: Long): Char = when { char in 'a'..'z' -> { val base = 'a'.code val offset = char.code - base val shifted = (offset + shift) % 26 (base + shifted).toChar() } + else -> char } + + diff --git a/contest/src/main/java/com/github/contest/strings/StringsProdVariant.kt b/contest/src/main/java/com/github/contest/strings/StringsProdVariant.kt new file mode 100644 index 00000000..f9382ac4 --- /dev/null +++ b/contest/src/main/java/com/github/contest/strings/StringsProdVariant.kt @@ -0,0 +1,2 @@ +package com.github.contest.strings + From 16f188197034ea96328f93e42413d8493c4d9bb1 Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Sat, 5 Apr 2025 08:25:05 +0100 Subject: [PATCH 08/30] add prod variant 848 --- .../contest/strings/StringsProdVariant.kt | 34 +++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/contest/src/main/java/com/github/contest/strings/StringsProdVariant.kt b/contest/src/main/java/com/github/contest/strings/StringsProdVariant.kt index f9382ac4..053d0c52 100644 --- a/contest/src/main/java/com/github/contest/strings/StringsProdVariant.kt +++ b/contest/src/main/java/com/github/contest/strings/StringsProdVariant.kt @@ -1,2 +1,36 @@ package com.github.contest.strings +/** + * 848. Shifting Letters + */ + +fun shiftingLetterProdVariant(str: String, shifts: IntArray): String { + var sum = shifts.toLongArray().sum() + return buildString { + str.forEachIndexed { index, letter -> + val new = letter.shiftLetter(sum) + append(new) + sum -= shifts[index] + } + } +} + +private fun IntArray.toLongArray(): LongArray { + val new = LongArray(this.size) + for (i in indices) { + new[i] = this[i].toLong() + } + + return new +} + +private fun Char.shiftLetter(shift: Long): Char = when { + this in 'a'..'z' -> { + val base = 'a'.code + val offset = this.code - base + val shifted = (offset + shift) % 26 + (base + shifted).toChar() + } + + else -> this +} \ No newline at end of file From 24a01b6f570b65a372df4628c8e0c1a7f044b7d1 Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Sat, 5 Apr 2025 08:26:04 +0100 Subject: [PATCH 09/30] small change --- .../main/java/com/github/contest/strings/StringsProdVariant.kt | 1 + 1 file changed, 1 insertion(+) diff --git a/contest/src/main/java/com/github/contest/strings/StringsProdVariant.kt b/contest/src/main/java/com/github/contest/strings/StringsProdVariant.kt index 053d0c52..768903e5 100644 --- a/contest/src/main/java/com/github/contest/strings/StringsProdVariant.kt +++ b/contest/src/main/java/com/github/contest/strings/StringsProdVariant.kt @@ -2,6 +2,7 @@ package com.github.contest.strings /** * 848. Shifting Letters + * Prod Variant */ fun shiftingLetterProdVariant(str: String, shifts: IntArray): String { From 14cf3f6994110281d91b3ecdc97f7c6aee5c12d6 Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Sat, 5 Apr 2025 09:49:43 +0100 Subject: [PATCH 10/30] add 2734 --- .../github/contest/strings/StringsLeetcode.kt | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/contest/src/main/java/com/github/contest/strings/StringsLeetcode.kt b/contest/src/main/java/com/github/contest/strings/StringsLeetcode.kt index 46c2e8c3..2706ca90 100644 --- a/contest/src/main/java/com/github/contest/strings/StringsLeetcode.kt +++ b/contest/src/main/java/com/github/contest/strings/StringsLeetcode.kt @@ -39,5 +39,44 @@ private fun shiftLetter(char: Char, shift: Long): Char = when { else -> char } +/** + * 2734. Lexicographically Smallest String After Substring Operation + */ + +fun smallestString(s: String): String { + if (s.hasSingle()) return when { + s[0] == 'a' -> 'z'.toString() + else -> Char(s[0].code - 1).toString() + } + val chars = s.toCharArray() + val n = chars.size + var start = -1 + + for (i in 0 until n) { + if (chars[i] != 'a') { + start = i + break + } + } + + if (start == -1) { + chars[n - 1] = 'z' + return String(chars) + } + + for (i in start until n) { + if (chars[i] != 'a') chars[i]-- + else break + } + + return String(chars) + +} + +fun String.hasSingle(): Boolean = when { + this.length == 1 -> true + else -> false +} + From 13642b681048cbc801277cd297c621e5ec536204 Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Sat, 5 Apr 2025 10:23:41 +0100 Subject: [PATCH 11/30] add 2734 prod variant --- .../main/java/com/github/contest/Execute.kt | 27 ++----------------- .../contest/strings/StringsProdVariant.kt | 24 +++++++++++++++++ 2 files changed, 26 insertions(+), 25 deletions(-) diff --git a/contest/src/main/java/com/github/contest/Execute.kt b/contest/src/main/java/com/github/contest/Execute.kt index 32d1f7b8..4f3daf4b 100644 --- a/contest/src/main/java/com/github/contest/Execute.kt +++ b/contest/src/main/java/com/github/contest/Execute.kt @@ -2,6 +2,7 @@ package com.github.contest import com.github.contest.strings.shiftingLetters +import com.github.contest.strings.smallestStringProdVariant import java.util.TreeMap @@ -12,31 +13,7 @@ import java.util.TreeMap fun main() { - shiftingLetters( - "mkgfzkkuxownxvfvxasy", - intArrayOf( - 505870226, - 437526072, - 266740649, - 224336793, - 532917782, - 311122363, - 567754492, - 595798950, - 81520022, - 684110326, - 137742843, - 275267355, - 856903962, - 148291585, - 919054234, - 467541837, - 622939912, - 116899933, - 983296461, - 536563513 - ) - ).also { println(it) } + smallestStringProdVariant("acbcbabc").also { println(it) } } fun testing() { diff --git a/contest/src/main/java/com/github/contest/strings/StringsProdVariant.kt b/contest/src/main/java/com/github/contest/strings/StringsProdVariant.kt index 768903e5..f94a8152 100644 --- a/contest/src/main/java/com/github/contest/strings/StringsProdVariant.kt +++ b/contest/src/main/java/com/github/contest/strings/StringsProdVariant.kt @@ -34,4 +34,28 @@ private fun Char.shiftLetter(shift: Long): Char = when { } else -> this +} + +/** + * 2734. Lexicographically Smallest String After Substring Operation + * Prod Variant + */ + +fun smallestStringProdVariant(s: String): String { + val firstNonAIndex = s.indexOfFirst { it != 'a' } + + return if (firstNonAIndex == -1) { + s.dropLast(1) + 'z' + } else { + val modifiedChars = s.toCharArray().also { chars -> + for (i in firstNonAIndex until chars.size) { + if (chars[i] != 'a') { + chars[i]-- + } else { + break + } + } + } + String(modifiedChars) + } } \ No newline at end of file From f80280d46fdf2d84681331daeb89d1a7fcd08ad2 Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Sat, 5 Apr 2025 10:45:51 +0100 Subject: [PATCH 12/30] add 1863 --- .../main/java/com/github/contest/Execute.kt | 3 ++- .../BitManipulationLeetcode.kt | 23 +++++++++++++++++++ 2 files changed, 25 insertions(+), 1 deletion(-) diff --git a/contest/src/main/java/com/github/contest/Execute.kt b/contest/src/main/java/com/github/contest/Execute.kt index 4f3daf4b..fd25f043 100644 --- a/contest/src/main/java/com/github/contest/Execute.kt +++ b/contest/src/main/java/com/github/contest/Execute.kt @@ -1,6 +1,7 @@ package com.github.contest +import com.github.contest.bitManipulation.subsetXORSum import com.github.contest.strings.shiftingLetters import com.github.contest.strings.smallestStringProdVariant @@ -13,7 +14,7 @@ import java.util.TreeMap fun main() { - smallestStringProdVariant("acbcbabc").also { println(it) } + subsetXORSum(intArrayOf(5, 1, 6)) } fun testing() { diff --git a/contest/src/main/java/com/github/contest/bitManipulation/BitManipulationLeetcode.kt b/contest/src/main/java/com/github/contest/bitManipulation/BitManipulationLeetcode.kt index 11c0275f..e3a63857 100644 --- a/contest/src/main/java/com/github/contest/bitManipulation/BitManipulationLeetcode.kt +++ b/contest/src/main/java/com/github/contest/bitManipulation/BitManipulationLeetcode.kt @@ -1,2 +1,25 @@ package com.github.contest.bitManipulation +/** + * 1863. Sum of All Subset XOR Totals + */ + +fun subsetXORSum(nums: IntArray): Int { + var totalXORSum = 0 + + fun calculateSubsetXOR(index: Int, currentXOR: Int) { + if (index == nums.size) { + totalXORSum += currentXOR + return + } + + // Include the current element + calculateSubsetXOR(index + 1, currentXOR xor nums[index]) + + // Exclude the current element + calculateSubsetXOR(index + 1, currentXOR) + } + + calculateSubsetXOR(0, 0) + return totalXORSum +} \ No newline at end of file From f63e2c52ccbfc6ac4c9bbd00dca3d5c3d050cf38 Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Sat, 5 Apr 2025 11:39:01 +0100 Subject: [PATCH 13/30] add 2351 --- .../github/contest/hashTable/HashTableLeetcode.kt | 15 +++++++++++++++ 1 file changed, 15 insertions(+) diff --git a/contest/src/main/java/com/github/contest/hashTable/HashTableLeetcode.kt b/contest/src/main/java/com/github/contest/hashTable/HashTableLeetcode.kt index 6556bc79..aaf90379 100644 --- a/contest/src/main/java/com/github/contest/hashTable/HashTableLeetcode.kt +++ b/contest/src/main/java/com/github/contest/hashTable/HashTableLeetcode.kt @@ -256,4 +256,19 @@ fun findMissingAndRepeatedValues(grid: Array): IntArray { } return res +} + +/** + * 2351. First Letter to Appear Twice + */ + +fun repeatedCharacter(s: String): Char { + val alphabet = IntArray(26) + for (char in s) { + val index = char - 'a' + if (alphabet[index] == 0) alphabet[index] += 1 + else return char + } + + return 'a' } \ No newline at end of file From 6a0223f989ac334bf197a79060074b8c8e9923d1 Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Sat, 5 Apr 2025 11:48:38 +0100 Subject: [PATCH 14/30] add 2278 --- .../java/com/github/contest/strings/StringsLeetcode.kt | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/contest/src/main/java/com/github/contest/strings/StringsLeetcode.kt b/contest/src/main/java/com/github/contest/strings/StringsLeetcode.kt index 2706ca90..c3f38ce1 100644 --- a/contest/src/main/java/com/github/contest/strings/StringsLeetcode.kt +++ b/contest/src/main/java/com/github/contest/strings/StringsLeetcode.kt @@ -78,5 +78,15 @@ fun String.hasSingle(): Boolean = when { else -> false } +/** + * 2278. Percentage of Letter in String + */ + +fun percentageLetter(s: String, letter: Char): Int { + var count = 0 + for (char in s) if (char == letter) count++ + return if (count == 0) 0 else (count * 100) / s.length +} + From ce0aab7d204c0e6f4327d772fdf43a2f8bb19f78 Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Sat, 5 Apr 2025 18:54:14 +0100 Subject: [PATCH 15/30] add 2140 prod variant with custom ext --- .../com/github/contest/dp/DpProdVariant.kt | 26 +++++++++++++++++++ 1 file changed, 26 insertions(+) diff --git a/contest/src/main/java/com/github/contest/dp/DpProdVariant.kt b/contest/src/main/java/com/github/contest/dp/DpProdVariant.kt index 1a60b05a..f0fdebee 100644 --- a/contest/src/main/java/com/github/contest/dp/DpProdVariant.kt +++ b/contest/src/main/java/com/github/contest/dp/DpProdVariant.kt @@ -148,4 +148,30 @@ fun longestArithSeqLengthProdVariant(nums: IntArray): Int { len } } +} + +/** + * 2140. Solving Questions With Brainpower + * Prod Variant + */ + + +fun mostPointsProdVariant(questions: Array): Long { + val n = questions.size + val dp = LongArray(n) + questions.forEachReversedIndexed { index, arr -> + val points = arr[0] + val brainpower = arr[1] + dp[index] = points + when { + brainpower + index + 1 < n -> dp[brainpower + index + 1] + else -> 0L + } + dp[index] = maxOf(dp[index], dp[index + 1]) + } + + return dp.first() +} + +fun Array.forEachReversedIndexed(action: (Int, T) -> Unit) { + for (i in indices) action(i, this[i]) } \ No newline at end of file From b14e5053a200cc161065685a06e2401dd8b9fe55 Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Sat, 5 Apr 2025 18:59:37 +0100 Subject: [PATCH 16/30] small change --- contest/src/main/java/com/github/contest/dp/DpProdVariant.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contest/src/main/java/com/github/contest/dp/DpProdVariant.kt b/contest/src/main/java/com/github/contest/dp/DpProdVariant.kt index f0fdebee..461786fb 100644 --- a/contest/src/main/java/com/github/contest/dp/DpProdVariant.kt +++ b/contest/src/main/java/com/github/contest/dp/DpProdVariant.kt @@ -158,7 +158,7 @@ fun longestArithSeqLengthProdVariant(nums: IntArray): Int { fun mostPointsProdVariant(questions: Array): Long { val n = questions.size - val dp = LongArray(n) + val dp = LongArray(n + 1) questions.forEachReversedIndexed { index, arr -> val points = arr[0] val brainpower = arr[1] @@ -173,5 +173,5 @@ fun mostPointsProdVariant(questions: Array): Long { } fun Array.forEachReversedIndexed(action: (Int, T) -> Unit) { - for (i in indices) action(i, this[i]) + for (i in this.size - 1 downTo 0) action(i, this[i]) } \ No newline at end of file From 7ef2cd4a5f22e5022daa1ac7c7755fd8320ae053 Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Sun, 6 Apr 2025 20:28:15 +0100 Subject: [PATCH 17/30] add new file and 165 --- .../contest/twoPointer/TwoPointerLeetCode.kt | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) create mode 100644 contest/src/main/java/com/github/contest/twoPointer/TwoPointerLeetCode.kt diff --git a/contest/src/main/java/com/github/contest/twoPointer/TwoPointerLeetCode.kt b/contest/src/main/java/com/github/contest/twoPointer/TwoPointerLeetCode.kt new file mode 100644 index 00000000..4ef2afc6 --- /dev/null +++ b/contest/src/main/java/com/github/contest/twoPointer/TwoPointerLeetCode.kt @@ -0,0 +1,22 @@ +package com.github.contest.twoPointer + +/** + * 165. Compare Version Numbers + */ + +fun compareVersion(version1: String, version2: String): Int { + val firstNumber = version1.split(".").map { it.toInt() } + val secondNumber = version2.split(".").map { it.toInt() } + + for (i in 0 until maxOf(firstNumber.size, secondNumber.size)) { + val p1 = if (i < firstNumber.size) firstNumber[i] else 0 + val p2 = if (i < secondNumber.size) secondNumber[i] else 0 + + when { + p1 != p2 -> { + return if (p1 > p2) 1 else -1 + } + } + } + return 0 +} \ No newline at end of file From c01c5896e814ded8cdcd70264c4db0bd2d7a5cbd Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Mon, 7 Apr 2025 20:34:55 +0100 Subject: [PATCH 18/30] add 981 --- .../main/java/com/github/contest/Execute.kt | 7 ++-- .../github/contest/design/DesignLeetcode.kt | 35 +++++++++++++++++++ 2 files changed, 37 insertions(+), 5 deletions(-) diff --git a/contest/src/main/java/com/github/contest/Execute.kt b/contest/src/main/java/com/github/contest/Execute.kt index fd25f043..bd043331 100644 --- a/contest/src/main/java/com/github/contest/Execute.kt +++ b/contest/src/main/java/com/github/contest/Execute.kt @@ -1,10 +1,7 @@ package com.github.contest -import com.github.contest.bitManipulation.subsetXORSum -import com.github.contest.strings.shiftingLetters -import com.github.contest.strings.smallestStringProdVariant - +import com.github.contest.strings.isNumber import java.util.TreeMap @@ -14,7 +11,7 @@ import java.util.TreeMap fun main() { - subsetXORSum(intArrayOf(5, 1, 6)) + isNumber("6+1").also { println(it) } } fun testing() { diff --git a/contest/src/main/java/com/github/contest/design/DesignLeetcode.kt b/contest/src/main/java/com/github/contest/design/DesignLeetcode.kt index fa3b3697..8542f2db 100644 --- a/contest/src/main/java/com/github/contest/design/DesignLeetcode.kt +++ b/contest/src/main/java/com/github/contest/design/DesignLeetcode.kt @@ -117,4 +117,39 @@ class Trie() { return curr } +} + +/** + * 981. Time Based Key-Value Store + */ + +class TimeMap() { + + private val store = mutableMapOf>>() + + fun set(key: String, value: String, timestamp: Int) { + store.getOrPut(key) { mutableListOf(Pair(timestamp, value)) }.add(Pair(timestamp, value)) + } + + fun get(key: String, timestamp: Int): String { + val list = store[key] ?: return emptyString() + var left = 0 + var right = list.size - 1 + var res = emptyString() + + while (left <= right) { + val mid = (left + right) / 2 + val (currentTimeStamp, currentValue) = list[mid] + if (currentTimeStamp == timestamp) return currentValue + if (currentTimeStamp < timestamp) { + left = mid + 1 + res = currentValue + } else right = mid + } + + return res + } + + private fun emptyString() = "" + } \ No newline at end of file From 4a90ba1e78c43dc87b40731ff1121f28029a8410 Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Tue, 8 Apr 2025 10:18:05 +0100 Subject: [PATCH 19/30] add prod variant for 981 --- .../contest/design/DesignProdVariant.kt | 39 +++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/contest/src/main/java/com/github/contest/design/DesignProdVariant.kt b/contest/src/main/java/com/github/contest/design/DesignProdVariant.kt index c346e0f0..cf173891 100644 --- a/contest/src/main/java/com/github/contest/design/DesignProdVariant.kt +++ b/contest/src/main/java/com/github/contest/design/DesignProdVariant.kt @@ -30,4 +30,43 @@ class ProductOfNumbersProdVariant() { } return products.last() / products[products.size - k - 1] } +} + +/** + * 981. Time Based Key-Value Store + * Prod Variant + */ + +class TimeMapProdVariant { + + private val store = mutableMapOf>>() + + fun set(key: String, value: String, timestamp: Int) { + store.getOrPut(key) { mutableListOf(Pair(timestamp, value)) }.also { + it.add(Pair(timestamp, value)) + } + } + + fun get(key: String, timestamp: Int): String = when { + store[key] == null -> "" + else -> getFromList(store.getOrDefault(key, listOf()), timestamp) + } + + private fun getFromList(list: List>, timestamp: Int): String = + list.binarySearch { + when { + it.first == timestamp -> 0 + it.first < timestamp -> -1 + else -> 1 + } + }.let { index -> + when { + index >= 0 -> list[index].second + else -> { + val insertionPoint = -index - 1 + if (insertionPoint == 0) "" else list[insertionPoint - 1].second + } + } + } + } \ No newline at end of file From cb0f583faa5ca9c96ad673b857056a1158313f79 Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Tue, 8 Apr 2025 11:35:14 +0100 Subject: [PATCH 20/30] add 1309 --- contest/src/main/java/com/github/contest/Execute.kt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/contest/src/main/java/com/github/contest/Execute.kt b/contest/src/main/java/com/github/contest/Execute.kt index bd043331..e8a72017 100644 --- a/contest/src/main/java/com/github/contest/Execute.kt +++ b/contest/src/main/java/com/github/contest/Execute.kt @@ -1,7 +1,7 @@ package com.github.contest -import com.github.contest.strings.isNumber +import com.github.contest.strings.freqAlphabets import java.util.TreeMap @@ -11,7 +11,7 @@ import java.util.TreeMap fun main() { - isNumber("6+1").also { println(it) } + freqAlphabets("12345678910#11#12#13#14#15#16#17#18#19#20#21#22#23#24#25#26#").also { println(it) } } fun testing() { From 966ff98d3b82ffd60e443d152ee2be25736901ca Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Tue, 8 Apr 2025 11:35:20 +0100 Subject: [PATCH 21/30] add 1309 --- .../github/contest/strings/StringsLeetcode.kt | 145 ++++++++++++++++++ 1 file changed, 145 insertions(+) diff --git a/contest/src/main/java/com/github/contest/strings/StringsLeetcode.kt b/contest/src/main/java/com/github/contest/strings/StringsLeetcode.kt index c3f38ce1..8028bcee 100644 --- a/contest/src/main/java/com/github/contest/strings/StringsLeetcode.kt +++ b/contest/src/main/java/com/github/contest/strings/StringsLeetcode.kt @@ -89,4 +89,149 @@ fun percentageLetter(s: String, letter: Char): Int { } +/** + * 1309. Decrypt String from Alphabet to Integer Mapping + */ + +fun freqAlphabets(s: String): String { + val result = StringBuilder() + var i = s.length - 1 + + while (i >= 0) { + if (s[i] == '#') { + val twoDigit = s.substring(i - 2, i).toInt() + result.append(getLetterFromIndex(twoDigit - 1)) + i -= 3 + } else { + result.append(getLetterFromIndex(s[i].digitToInt() - 1)) + i -= 1 + } + } + + return result.reverse().toString() +} + +fun getLetterFromIndex(index: Int): Char { + require(index in 0..25) { "Index must be between 0 and 25 (inclusive)" } + return 'a' + index +} + + +/** + * + */ + +fun isNumber(s: String): Boolean = when { + isOnlyNumbers(s) -> true + hasLetter(s) -> false + isValidNumberSign(s) && !hasExponential(s) -> true + isNotValidNumberSign(s) -> false + else -> hasNumberExponential(s) +} + +private fun hasNumberExponential(str: String): Boolean { + var indexExp = 0 + var isNotDigits = true + for (i in str.indices) { + if (isExponential(str[i])) { + indexExp = i + break + } + } + + for (i in 0 until indexExp) { + if (isDigit(str[i])) isNotDigits = false + } + + if (isNotDigits) return false + isNotDigits = true + for (i in indexExp until str.length) { + if (str[i] == '.') return false + if (isDigit(str[i])) isNotDigits = false + } + + return !isNotDigits +} + +private fun isValidNumberSign(str: String): Boolean { + var isPlusOrMinus = false + var isOneDot = false + for (char in str) { + if (isSign(char)) { + if (isPlusOrMinus) return false + else isPlusOrMinus = true + } + if (isDot(char) && !isOneDot) { + isOneDot = true + continue + } + if (isDot(char) && isOneDot) return false + } + return true +} + +private fun hasExponential(str: String): Boolean { + for (char in str) if (isExponential(char)) return true + return false +} + +private fun isNotValidNumberSign(str: String): Boolean { + var isPlusOrMinus = false + var isOneDot = false + for (char in str) { + if (isSign(char)) { + if (isPlusOrMinus) return true + else isPlusOrMinus = true + } + if (isDot(char) && !isOneDot) { + isOneDot = true + continue + } + if (isOneDot) return true + } + return false +} + +private fun hasLetter(str: String): Boolean { + for (char in str) { + if (isLetter(char)) return true + } + return false +} + +private fun isOnlyNumbers(str: String): Boolean { + for (char in str) { + if (isLetter(char) || isExponential(char) || isSign(char) || isDot(char)) return false + } + return true +} + +fun isDigit(char: Char): Boolean = when { + char in '0'..'9' -> true + else -> false +} + +fun isLetter(char: Char): Boolean = when { + (char != 'e' && char != 'E') && (char in 'a'..'z' || char in 'A'..'Z') -> true + else -> false +} + +fun isExponential(char: Char): Boolean = when { + char == 'e' || char == 'E' -> true + else -> false +} + +fun isDot(char: Char) = when { + char == '.' -> true + else -> false +} + +fun isSign(char: Char): Boolean { + return when { + char == '+' || char == '-' -> true + else -> false + } +} + + From f5d3e1e91dbf122a26c6f3d6624b6123a0ab0880 Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Tue, 8 Apr 2025 12:41:05 +0100 Subject: [PATCH 22/30] add 3396 --- .../main/java/com/github/contest/Execute.kt | 4 +- .../contest/hashTable/HashTableLeetcode.kt | 41 +++++++++++++++++++ 2 files changed, 43 insertions(+), 2 deletions(-) diff --git a/contest/src/main/java/com/github/contest/Execute.kt b/contest/src/main/java/com/github/contest/Execute.kt index e8a72017..37e1ba87 100644 --- a/contest/src/main/java/com/github/contest/Execute.kt +++ b/contest/src/main/java/com/github/contest/Execute.kt @@ -1,7 +1,7 @@ package com.github.contest -import com.github.contest.strings.freqAlphabets +import com.github.contest.hashTable.minimumOperations import java.util.TreeMap @@ -11,7 +11,7 @@ import java.util.TreeMap fun main() { - freqAlphabets("12345678910#11#12#13#14#15#16#17#18#19#20#21#22#23#24#25#26#").also { println(it) } + minimumOperations(intArrayOf(1, 2, 3, 4, 2, 3, 3, 5, 7)).also { println(it) } } fun testing() { diff --git a/contest/src/main/java/com/github/contest/hashTable/HashTableLeetcode.kt b/contest/src/main/java/com/github/contest/hashTable/HashTableLeetcode.kt index aaf90379..d9980a9f 100644 --- a/contest/src/main/java/com/github/contest/hashTable/HashTableLeetcode.kt +++ b/contest/src/main/java/com/github/contest/hashTable/HashTableLeetcode.kt @@ -271,4 +271,45 @@ fun repeatedCharacter(s: String): Char { } return 'a' +} + +/** + * 3396. Minimum Number of Operations to Make Elements in Array Distinct + */ + +fun minimumOperations(nums: IntArray): Int { + val map = mutableMapOf() + var operations = 0 + + for (num in nums) map[num] = map.getOrDefault(num, 0) + 1 + + if (map.size == nums.size) return 0 + + for (i in nums.indices step 3) { + if (i + 2 < nums.size) { + val one = nums[i] + val two = nums[i + 1] + val three = nums[i + 2] + map.reduceOrRemove(one) + map.reduceOrRemove(two) + map.reduceOrRemove(three) + var isUnique = true + for (value in map.values) { + if (value > 1) { + isUnique = false + break + } + } + if (isUnique) return operations + 1 + operations++ + } + } + + return if (map.size > 0) operations + 1 else operations + +} + +private fun MutableMap.reduceOrRemove(key: Int) { + this[key] = this.getOrDefault(key, 0) - 1 + if (this.getOrDefault(key, 0) == 0) this.remove(key) } \ No newline at end of file From 8adb8c07147fb20a9bd7f966bda142c85f9944d4 Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Tue, 8 Apr 2025 14:33:39 +0100 Subject: [PATCH 23/30] add 242 --- .../contest/hashTable/HashTableLeetcode.kt | 21 ++++++++++++++++++- 1 file changed, 20 insertions(+), 1 deletion(-) diff --git a/contest/src/main/java/com/github/contest/hashTable/HashTableLeetcode.kt b/contest/src/main/java/com/github/contest/hashTable/HashTableLeetcode.kt index d9980a9f..8647bbc5 100644 --- a/contest/src/main/java/com/github/contest/hashTable/HashTableLeetcode.kt +++ b/contest/src/main/java/com/github/contest/hashTable/HashTableLeetcode.kt @@ -305,11 +305,30 @@ fun minimumOperations(nums: IntArray): Int { } } - return if (map.size > 0) operations + 1 else operations + return if (map.isNotEmpty()) operations + 1 else operations } private fun MutableMap.reduceOrRemove(key: Int) { this[key] = this.getOrDefault(key, 0) - 1 if (this.getOrDefault(key, 0) == 0) this.remove(key) +} + +/** + * 242. Valid Anagram + */ + +fun isAnagram(s: String, t: String): Boolean { + if (s.length != t.length) return false + val first = IntArray(26) + val second = IntArray(26) + + for (char in s) first[char - 'a']++ + for (char in t) second[char - 'a']++ + + for (char in t) { + if (first[char - 'a'] == 0 || first[char - 'a'] != second[char - 'a']) return false + } + + return true } \ No newline at end of file From c2b8615e28a30411bf72b6a58e19f16e079bbce5 Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Tue, 8 Apr 2025 15:11:22 +0100 Subject: [PATCH 24/30] add new files and prod variant's and change 347 problem --- .../com/leetcode_kotlin/AlgorithmLeetcode.kt | 25 ---------------- .../priorityqueue/PriorityQueueLeetcode.kt | 29 +++++++++++++++++++ .../priorityqueue/PriorityQueueProdVariant.kt | 18 ++++++++++++ 3 files changed, 47 insertions(+), 25 deletions(-) create mode 100644 contest/src/main/java/com/github/contest/priorityqueue/PriorityQueueLeetcode.kt create mode 100644 contest/src/main/java/com/github/contest/priorityqueue/PriorityQueueProdVariant.kt diff --git a/app/src/main/java/com/leetcode_kotlin/AlgorithmLeetcode.kt b/app/src/main/java/com/leetcode_kotlin/AlgorithmLeetcode.kt index 1187a83a..3127f6ed 100644 --- a/app/src/main/java/com/leetcode_kotlin/AlgorithmLeetcode.kt +++ b/app/src/main/java/com/leetcode_kotlin/AlgorithmLeetcode.kt @@ -2612,31 +2612,6 @@ fun findRelativeRanks(score: IntArray): Array { return ans } -/** - * 347. Top K Frequent Elements - */ - -fun topKFrequent(nums: IntArray, k: Int): IntArray? { - val map: MutableMap = HashMap() - for (n in nums) { - map[n] = map.getOrDefault(n, 0) + 1 - } - - val heap = PriorityQueue { a: Map.Entry, b: Map.Entry -> - b.value.compareTo(a.value) - } - - for (entry in map.entries) { - heap.offer(entry) - } - - val res = IntArray(k) - for (i in 0 until k) { - res[i] = heap.poll().key - } - - return res -} /** * 437. Path Sum III diff --git a/contest/src/main/java/com/github/contest/priorityqueue/PriorityQueueLeetcode.kt b/contest/src/main/java/com/github/contest/priorityqueue/PriorityQueueLeetcode.kt new file mode 100644 index 00000000..3f186a3b --- /dev/null +++ b/contest/src/main/java/com/github/contest/priorityqueue/PriorityQueueLeetcode.kt @@ -0,0 +1,29 @@ +package com.github.contest.priorityqueue + +import java.util.PriorityQueue + +/** + * 347. Top K Frequent Elements + */ + +fun topKFrequent(nums: IntArray, k: Int): IntArray? { + val map: MutableMap = HashMap() + for (n in nums) { + map[n] = map.getOrDefault(n, 0) + 1 + } + + val heap = PriorityQueue { a: Map.Entry, b: Map.Entry -> + b.value.compareTo(a.value) + } + + for (entry in map.entries) { + heap.offer(entry) + } + + val res = IntArray(k) + for (i in 0 until k) { + res[i] = heap.poll().key + } + + return res +} \ No newline at end of file diff --git a/contest/src/main/java/com/github/contest/priorityqueue/PriorityQueueProdVariant.kt b/contest/src/main/java/com/github/contest/priorityqueue/PriorityQueueProdVariant.kt new file mode 100644 index 00000000..2869c722 --- /dev/null +++ b/contest/src/main/java/com/github/contest/priorityqueue/PriorityQueueProdVariant.kt @@ -0,0 +1,18 @@ +package com.github.contest.priorityqueue + +/** + * 347. Top K Frequent Elements + */ + +fun topKFrequentProdVariant(nums: IntArray, k: Int): IntArray { + val freq = mutableMapOf() + val repeated = Array>(nums.size + 1) {mutableListOf()} + + for (num in nums) freq[num] = freq.getOrDefault(num, 0) + 1 + + for ((num, count) in freq) { + repeated[count].add(num) + } + + return repeated.flatMap {it}.takeLast(k).toIntArray() +} \ No newline at end of file From d4deeba2f04acefffc8b5f80cafeaeda5b61a19e Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Wed, 9 Apr 2025 10:19:26 +0100 Subject: [PATCH 25/30] add 76 problem --- .../main/java/com/github/contest/Execute.kt | 6 ++- .../slidingWindow/SlidingWindowLeetcode.kt | 54 +++++++++++++++++++ 2 files changed, 58 insertions(+), 2 deletions(-) diff --git a/contest/src/main/java/com/github/contest/Execute.kt b/contest/src/main/java/com/github/contest/Execute.kt index 37e1ba87..8a841fa5 100644 --- a/contest/src/main/java/com/github/contest/Execute.kt +++ b/contest/src/main/java/com/github/contest/Execute.kt @@ -1,7 +1,7 @@ package com.github.contest -import com.github.contest.hashTable.minimumOperations +import com.github.contest.slidingWindow.minWindow import java.util.TreeMap @@ -11,7 +11,9 @@ import java.util.TreeMap fun main() { - minimumOperations(intArrayOf(1, 2, 3, 4, 2, 3, 3, 5, 7)).also { println(it) } + val s = "a" + val t = "a" + minWindow(s, t).also { println(it) } } fun testing() { diff --git a/contest/src/main/java/com/github/contest/slidingWindow/SlidingWindowLeetcode.kt b/contest/src/main/java/com/github/contest/slidingWindow/SlidingWindowLeetcode.kt index 56d96739..915681b5 100644 --- a/contest/src/main/java/com/github/contest/slidingWindow/SlidingWindowLeetcode.kt +++ b/contest/src/main/java/com/github/contest/slidingWindow/SlidingWindowLeetcode.kt @@ -1,2 +1,56 @@ package com.github.contest.slidingWindow +/** + * 76. Minimum Window Substring + */ + +fun minWindow(s: String, t: String): String { + if (t.length > s.length) return "" + val store = mutableMapOf() + + store.fillMapFromString(t) + + for (k in t.length..s.length) { + val cache = mutableMapOf() + var left = 0 + for (right in s.indices) { + val key = s[right] + cache[key] = cache.getOrDefault(key, 0) + 1 + if ((right - left) == (k - 1)) { + val isUnique = checkUniqueAnswer(store, cache) + if (isUnique) return s.substring(left, right + 1) + cache.reduceOrRemove(s[left]) + left++ + } + } + } + + return "" +} + +private fun MutableMap.fillMapFromString(str: String) { + for (char in str) this[char] = this.getOrDefault(char, 0) + 1 +} + +private fun MutableMap.reduceOrRemove(key: Char) { + this[key] = this.getOrDefault(key, 0) - 1 + if (this[key] == 0) this.remove(key) +} + +private fun checkUniqueAnswer(store: MutableMap, cache: MutableMap): Boolean { + var isUnique = true + for ((char, count) in store) { + if (cache.contains(char)) { + val cacheCount = cache.getOrDefault(char, 0) + if (cacheCount < count) { + isUnique = false + break + } + } else { + isUnique = false + break + } + } + + return isUnique +} \ No newline at end of file From 7a8209cbb3aeea82f774e40042bfa9bc77c4e164 Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Wed, 9 Apr 2025 15:05:38 +0100 Subject: [PATCH 26/30] add base structure for sliding window problems --- .idea/misc.xml | 2 +- .../main/java/com/github/contest/Execute.kt | 8 +-- .../SlidingWindowAlternativeSolution.kt | 50 +++++++++++++++++++ .../slidingWindow/SlidingWindowProdVariant.kt | 5 ++ 4 files changed, 60 insertions(+), 5 deletions(-) create mode 100644 contest/src/main/java/com/github/contest/slidingWindow/SlidingWindowAlternativeSolution.kt create mode 100644 contest/src/main/java/com/github/contest/slidingWindow/SlidingWindowProdVariant.kt diff --git a/.idea/misc.xml b/.idea/misc.xml index 9f71c83d..0ad17cbd 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -1,7 +1,7 @@ - + diff --git a/contest/src/main/java/com/github/contest/Execute.kt b/contest/src/main/java/com/github/contest/Execute.kt index 8a841fa5..3264572d 100644 --- a/contest/src/main/java/com/github/contest/Execute.kt +++ b/contest/src/main/java/com/github/contest/Execute.kt @@ -1,7 +1,7 @@ package com.github.contest -import com.github.contest.slidingWindow.minWindow +import com.github.contest.slidingWindow.minWindowOptimumSolution import java.util.TreeMap @@ -11,9 +11,9 @@ import java.util.TreeMap fun main() { - val s = "a" - val t = "a" - minWindow(s, t).also { println(it) } + val s = "ADOBECODEBANC" + val t = "ABC" + minWindowOptimumSolution(s, t).also { println(it) } } fun testing() { diff --git a/contest/src/main/java/com/github/contest/slidingWindow/SlidingWindowAlternativeSolution.kt b/contest/src/main/java/com/github/contest/slidingWindow/SlidingWindowAlternativeSolution.kt new file mode 100644 index 00000000..1baec341 --- /dev/null +++ b/contest/src/main/java/com/github/contest/slidingWindow/SlidingWindowAlternativeSolution.kt @@ -0,0 +1,50 @@ +package com.github.contest.slidingWindow + + +/** + * + */ + +fun minWindowOptimumSolution(s: String, t: String): String { + if (s.isEmpty() || t.isEmpty()) return "" + + val targetMap = mutableMapOf() + for (char in t) { + targetMap[char] = targetMap.getOrDefault(char, 0) + 1 + } + + var left = 0 + var right = 0 + var minLength = Int.MAX_VALUE + var minStart = 0 + val required = targetMap.size + var formed = 0 + val windowCounts = mutableMapOf() + + while (right < s.length) { + val char = s[right] + windowCounts[char] = windowCounts.getOrDefault(char, 0) + 1 + + if (targetMap.containsKey(char) && windowCounts[char] == targetMap[char]) { + formed++ + } + + while (left <= right && formed == required) { + if (right - left + 1 < minLength) { + minLength = right - left + 1 + minStart = left + } + + val leftChar = s[left] + windowCounts[leftChar] = windowCounts.getOrDefault(leftChar, 0) - 1 + if (targetMap.containsKey(leftChar) && windowCounts[leftChar]!! < targetMap[leftChar]!!) { + formed-- + } + left++ + } + + right++ + } + + return if (minLength == Int.MAX_VALUE) "" else s.substring(minStart, minStart + minLength) +} \ No newline at end of file diff --git a/contest/src/main/java/com/github/contest/slidingWindow/SlidingWindowProdVariant.kt b/contest/src/main/java/com/github/contest/slidingWindow/SlidingWindowProdVariant.kt new file mode 100644 index 00000000..0cac09ab --- /dev/null +++ b/contest/src/main/java/com/github/contest/slidingWindow/SlidingWindowProdVariant.kt @@ -0,0 +1,5 @@ +package com.github.contest.slidingWindow + +/** + * + */ \ No newline at end of file From b6d04a4a8a3f3ffa248194ec51a1d4e295dac594 Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Thu, 10 Apr 2025 15:16:06 +0100 Subject: [PATCH 27/30] add 76 optimum solution --- .../contest/slidingWindow/SlidingWindowAlternativeSolution.kt | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/contest/src/main/java/com/github/contest/slidingWindow/SlidingWindowAlternativeSolution.kt b/contest/src/main/java/com/github/contest/slidingWindow/SlidingWindowAlternativeSolution.kt index 1baec341..7c2747ab 100644 --- a/contest/src/main/java/com/github/contest/slidingWindow/SlidingWindowAlternativeSolution.kt +++ b/contest/src/main/java/com/github/contest/slidingWindow/SlidingWindowAlternativeSolution.kt @@ -2,7 +2,8 @@ package com.github.contest.slidingWindow /** - * + * 76. Minimum Window Substring + * Optimum Solution O(n + m) */ fun minWindowOptimumSolution(s: String, t: String): String { @@ -21,6 +22,7 @@ fun minWindowOptimumSolution(s: String, t: String): String { var formed = 0 val windowCounts = mutableMapOf() + while (right < s.length) { val char = s[right] windowCounts[char] = windowCounts.getOrDefault(char, 0) + 1 From dca76561856a3c34deccb1b7e115c8363c52a427 Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Fri, 11 Apr 2025 15:29:30 +0100 Subject: [PATCH 28/30] add 2843 --- .idea/gradle.xml | 2 +- .idea/misc.xml | 1 - .../main/java/com/github/contest/Execute.kt | 22 ++++--- .../com/github/contest/math/MathLeetcode.kt | 66 +++++++++++++++++++ 4 files changed, 79 insertions(+), 12 deletions(-) diff --git a/.idea/gradle.xml b/.idea/gradle.xml index 96ccfae7..bfe173f1 100644 --- a/.idea/gradle.xml +++ b/.idea/gradle.xml @@ -4,7 +4,6 @@ diff --git a/.idea/misc.xml b/.idea/misc.xml index 0ad17cbd..8978d23d 100644 --- a/.idea/misc.xml +++ b/.idea/misc.xml @@ -1,4 +1,3 @@ - diff --git a/contest/src/main/java/com/github/contest/Execute.kt b/contest/src/main/java/com/github/contest/Execute.kt index 3264572d..d0a695a4 100644 --- a/contest/src/main/java/com/github/contest/Execute.kt +++ b/contest/src/main/java/com/github/contest/Execute.kt @@ -1,7 +1,8 @@ package com.github.contest -import com.github.contest.slidingWindow.minWindowOptimumSolution +import com.github.contest.math.countSymmetricIntegers +import com.github.contest.math.numberOfPowerfulInt import java.util.TreeMap @@ -11,19 +12,20 @@ import java.util.TreeMap fun main() { - val s = "ADOBECODEBANC" - val t = "ABC" - minWindowOptimumSolution(s, t).also { println(it) } + countSymmetricIntegers(1, 10000).also { println(it) } + } -fun testing() { - val list = listOf(1, 2, 3) - list.reduceRight { i, acc -> - println("$i, $acc") - acc - i - }.also { println(it) } +fun numberOfPowerfulIntData() { + val start = 141L + val finish = 148L + val limit = 9 + val s = "9" + + numberOfPowerfulInt(start, finish, limit, s).also { println(it) } } + fun generateTesting() { val sequence = sequenceOf(3, 5, 6, 7, 7, 8, 8, 8, 9, 3) sequence.map { it * 2 }.filter { it > 3 }.filter { it > 2 }.constrainOnce() diff --git a/contest/src/main/java/com/github/contest/math/MathLeetcode.kt b/contest/src/main/java/com/github/contest/math/MathLeetcode.kt index da262b3d..5a5b5e1b 100644 --- a/contest/src/main/java/com/github/contest/math/MathLeetcode.kt +++ b/contest/src/main/java/com/github/contest/math/MathLeetcode.kt @@ -100,3 +100,69 @@ fun minOperations(grid: Array, x: Int): Int { } return ans } + +/** + * + */ + +fun numberOfPowerfulInt(start: Long, finish: Long, limit: Int, s: String): Long { + var num = s.toLong() + var counter = 0L + var powerful = num + var factor = 10 + + if (num > finish || "$limit$num".toLong() < start) return 0L + if (start == finish || num == finish) return 1L + + while (num < finish) { + var count = limit + powerful = "$count$powerful".toLong() + while (powerful > finish && count != 0) { + count-- + powerful = "$count$num".toLong() + } + if (count == 0) { + + } + if (counter == 0L) counter += count + else { + val temp = count * factor + counter += temp + factor *= 10 + } + num = powerful + } + + return if (s.toLong() in start..finish) counter + 1L else counter +} + +/** + * 2843. Count Symmetric Integers + */ + +fun countSymmetricIntegers(low: Int, high: Int): Int { + var count = 0 + + for (num in low..high) { + val digits = num.toString().length + when { + digits == 2 -> { + val first = num / 10 + val second = num % 10 + if (first == second) count++ + } + + digits == 4 -> { + val onePart = num / 100 + val twoPart = num % 100 + val first = onePart / 10 + onePart % 10 + val second = twoPart / 10 + twoPart % 10 + if (first == second) count++ + } + + else -> continue + } + } + + return count +} From 9441162a1be75ed1db2ca88bf72f4b7dfc74e9a4 Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Fri, 11 Apr 2025 15:30:06 +0100 Subject: [PATCH 29/30] small change and save state --- .../com/github/contest/math/MathLeetcode.kt | 62 +++++++++---------- 1 file changed, 31 insertions(+), 31 deletions(-) diff --git a/contest/src/main/java/com/github/contest/math/MathLeetcode.kt b/contest/src/main/java/com/github/contest/math/MathLeetcode.kt index 5a5b5e1b..39ac2eac 100644 --- a/contest/src/main/java/com/github/contest/math/MathLeetcode.kt +++ b/contest/src/main/java/com/github/contest/math/MathLeetcode.kt @@ -101,6 +101,37 @@ fun minOperations(grid: Array, x: Int): Int { return ans } +/** + * 2843. Count Symmetric Integers + */ + +fun countSymmetricIntegers(low: Int, high: Int): Int { + var count = 0 + + for (num in low..high) { + val digits = num.toString().length + when (digits) { + 2 -> { + val first = num / 10 + val second = num % 10 + if (first == second) count++ + } + + 4 -> { + val onePart = num / 100 + val twoPart = num % 100 + val first = onePart / 10 + onePart % 10 + val second = twoPart / 10 + twoPart % 10 + if (first == second) count++ + } + + else -> continue + } + } + + return count +} + /** * */ @@ -135,34 +166,3 @@ fun numberOfPowerfulInt(start: Long, finish: Long, limit: Int, s: String): Long return if (s.toLong() in start..finish) counter + 1L else counter } - -/** - * 2843. Count Symmetric Integers - */ - -fun countSymmetricIntegers(low: Int, high: Int): Int { - var count = 0 - - for (num in low..high) { - val digits = num.toString().length - when { - digits == 2 -> { - val first = num / 10 - val second = num % 10 - if (first == second) count++ - } - - digits == 4 -> { - val onePart = num / 100 - val twoPart = num % 100 - val first = onePart / 10 + onePart % 10 - val second = twoPart / 10 + twoPart % 10 - if (first == second) count++ - } - - else -> continue - } - } - - return count -} From 89ab3d1c4a98a9ff619c75cdc0090b065d462b1e Mon Sep 17 00:00:00 2001 From: Ashwagandha-coder Date: Sat, 12 Apr 2025 14:50:23 +0100 Subject: [PATCH 30/30] add 68 text justification --- .idea/gradle.xml | 2 +- .../main/java/com/github/contest/Execute.kt | 34 ++++- .../github/contest/strings/StringsLeetcode.kt | 139 ++++++++++++++++++ 3 files changed, 172 insertions(+), 3 deletions(-) diff --git a/.idea/gradle.xml b/.idea/gradle.xml index bfe173f1..96ccfae7 100644 --- a/.idea/gradle.xml +++ b/.idea/gradle.xml @@ -4,6 +4,7 @@ diff --git a/contest/src/main/java/com/github/contest/Execute.kt b/contest/src/main/java/com/github/contest/Execute.kt index d0a695a4..ac3e9cd8 100644 --- a/contest/src/main/java/com/github/contest/Execute.kt +++ b/contest/src/main/java/com/github/contest/Execute.kt @@ -1,8 +1,9 @@ package com.github.contest -import com.github.contest.math.countSymmetricIntegers import com.github.contest.math.numberOfPowerfulInt +import com.github.contest.strings.fullJustify +import com.github.contest.strings.subStrHash import java.util.TreeMap @@ -12,8 +13,37 @@ import java.util.TreeMap fun main() { - countSymmetricIntegers(1, 10000).also { println(it) } + fullJustify( + arrayOf( + "Science", + "is", + "what", + "we", + "understand", + "well", + "enough", + "to", + "explain", + "to", + "a", + "computer.", + "Art", + "is", + "everything", + "else", + "we", + "do" + ), 20 + ).also { + println( + it + ) + } + +} +fun subStrHashData() { + subStrHash("xxterzixjqrghqyeketqeynekvqhc", 15, 94, 4, 16).also { println(it) } } fun numberOfPowerfulIntData() { diff --git a/contest/src/main/java/com/github/contest/strings/StringsLeetcode.kt b/contest/src/main/java/com/github/contest/strings/StringsLeetcode.kt index 8028bcee..e11796dc 100644 --- a/contest/src/main/java/com/github/contest/strings/StringsLeetcode.kt +++ b/contest/src/main/java/com/github/contest/strings/StringsLeetcode.kt @@ -1,5 +1,7 @@ package com.github.contest.strings +import java.math.BigInteger + /** * 848. Shifting Letters */ @@ -233,5 +235,142 @@ fun isSign(char: Char): Boolean { } } +/** + * 68. Text Justification + */ + +fun fullJustify(words: Array, maxWidth: Int): List { + val res = mutableListOf() + var i = 0 + while (i < words.size) { + val cache = mutableListOf() + var len = 0 + while (i < words.size && len + words[i].length < maxWidth) { + len += words[i].length + 1 + cache.add(words[i]) + i++ + } + val str = when { + words.lastIteration(i) -> lastString(cache, maxWidth) + len + words[i].length == maxWidth -> { + cache.add(words[i]) + i++ + wordsFullOfMaxWidth(cache) + } + + else -> wordsNotFullOfMaxWidth(cache, maxWidth) + } + res.add(str) + } + + return res +} + +private fun Array.lastIteration(index: Int): Boolean = when { + index == this.size -> true + else -> false +} + +private fun wordsFullOfMaxWidth(store: List): String { + var res = "" + for (i in 0 until store.size - 1) { + res += store[i] + res += " " + } + res += store[store.size - 1] + return res +} + +private fun wordsNotFullOfMaxWidth(store: List, maxWidth: Int): String { + var res = "" + val len = sumOfLength(store) + val spaces = store.size - 1 + val partOfSpaces = maxWidth - len + + return when { + spaces == 0 -> { + for (word in store) res += word + repeat(partOfSpaces) { res += " " } + res + } + + partOfSpaces % spaces == 0 -> { + val distance = partOfSpaces / spaces + for (i in 0 until store.size - 1) { + res += store[i] + repeat(distance) { res += " " } + } + res += store[store.size - 1] + res + } + else -> { + var rest = partOfSpaces % spaces + val distance = partOfSpaces / spaces + for (i in 0 until store.size - 1) { + res += store[i] + if (rest != 0) { + repeat(distance + 1) { res += " " } + rest-- + } else repeat(distance) { res += " " } + } + res += store[store.size - 1] + res + } + } + +} + + +private fun lastString(store: List, maxWidth: Int): String { + var res = "" + for (i in 0 until store.size - 1) { + res += store[i] + res += " " + } + res += store[store.size - 1] + val diff = maxWidth - res.length + return if (diff == 0) res else { + repeat(diff) { res += " " } + res + } +} + +private fun sumOfLength(store: List): Int = store.sumOf { it.length } + +/** + * + */ + +fun subStrHash(s: String, power: Int, modulo: Int, k: Int, hashValue: Int): String { + var left = 0 + var temp = "" + + for (right in s.indices) { + temp += s[right] + if (right - left == k - 1) { + val hash = hash(temp, power, modulo) + if (hash.intValueExact() == hashValue.toBigInteger().intValueExact()) return temp + temp = temp.substring(1, temp.length) + left++ + } + } + + return "" +} + +private fun hash(str: String, power: Int, modulo: Int): BigInteger { + var res = 0.toBigInteger() + var pow = 0 + val power = power.toBigInteger() + for (element in str) { + val index = (element - 'a' + 1).toBigInteger() + val base = (power.pow(pow)) + val calc = index * base + res += calc + pow++ + } + + return res % modulo.toBigInteger() +}