diff --git a/kt/binary-tree-inorder-traversal.kt b/kt/binary-tree-inorder-traversal.kt index a1013f3..073db8b 100644 --- a/kt/binary-tree-inorder-traversal.kt +++ b/kt/binary-tree-inorder-traversal.kt @@ -9,7 +9,10 @@ * } */ class Solution { - fun inorderTraversal(root: TreeNode?, values: MutableList): List { + fun inorderTraversal( + root: TreeNode?, + values: MutableList, + ): List { if (root == null) { return values } @@ -21,6 +24,5 @@ class Solution { return values } - fun inorderTraversal(root: TreeNode?): List - = inorderTraversal(root, mutableListOf()) + fun inorderTraversal(root: TreeNode?): List = inorderTraversal(root, mutableListOf()) } diff --git a/kt/binary-tree-level-order-traversal.kt b/kt/binary-tree-level-order-traversal.kt index f8e4680..2a2733d 100644 --- a/kt/binary-tree-level-order-traversal.kt +++ b/kt/binary-tree-level-order-traversal.kt @@ -9,7 +9,11 @@ * } */ class Solution { - private fun levelOrder(root: TreeNode?, levels: MutableList>, level: Int): MutableList> { + private fun levelOrder( + root: TreeNode?, + levels: MutableList>, + level: Int, + ): MutableList> { if (root == null) { return levels } diff --git a/kt/check-if-every-row-and-column-contains-all-numbers.kt b/kt/check-if-every-row-and-column-contains-all-numbers.kt index 7ea64cf..7150dd4 100644 --- a/kt/check-if-every-row-and-column-contains-all-numbers.kt +++ b/kt/check-if-every-row-and-column-contains-all-numbers.kt @@ -3,11 +3,9 @@ class Solution { val n = matrix.size val required = (1..n).toSet() - fun checkDimension( - dimensions: Iterable> - ): Boolean = dimensions.all { it.toSet() == required } + fun checkDimension(dimensions: Iterable>): Boolean = dimensions.all { it.toSet() == required } return checkDimension(matrix.map(IntArray::toList)) && - checkDimension((0 until n).map { x -> matrix.map { row -> row[x] }}) + checkDimension((0 until n).map { x -> matrix.map { row -> row[x] } }) } } diff --git a/kt/construct-string-from-binary-tree.kt b/kt/construct-string-from-binary-tree.kt index 60669c4..f3d0c5c 100644 --- a/kt/construct-string-from-binary-tree.kt +++ b/kt/construct-string-from-binary-tree.kt @@ -18,7 +18,6 @@ class Solution { val left = "(${tree2str(root.left)})" val right = "(${tree2str(root.right)})" - if (left == "()" && right == "()") { return value } else if (right == "()") { diff --git a/kt/double-a-number-represented-as-a-linked-list.kt b/kt/double-a-number-represented-as-a-linked-list.kt index f2331ed..ecba255 100644 --- a/kt/double-a-number-represented-as-a-linked-list.kt +++ b/kt/double-a-number-represented-as-a-linked-list.kt @@ -19,7 +19,10 @@ fun toListNode(vararg xs: Int): ListNode? { return dummy.next } -fun linkedListEquals(head: ListNode?, xs: List): Boolean { +fun linkedListEquals( + head: ListNode?, + xs: List, +): Boolean { var node = head for ((i, x) in xs.withIndex()) { if (node == null) { diff --git a/kt/first-unique-character-in-a-string.kt b/kt/first-unique-character-in-a-string.kt index 49a44bd..b272c91 100644 --- a/kt/first-unique-character-in-a-string.kt +++ b/kt/first-unique-character-in-a-string.kt @@ -5,16 +5,17 @@ class Solution { } } - fun firstUniqChar(s: String): Int = s - .foldIndexed(mutableMapOf()) { i, acc, c -> - acc.getOrPut(c) { Accumulator(i) }.add() - acc - } - .filterValues { it.count == 1 } - .minByOrNull { (_, acc) -> acc.firstIndex } - ?.value - ?.firstIndex - ?: -1 + fun firstUniqChar(s: String): Int = + s + .foldIndexed(mutableMapOf()) { i, acc, c -> + acc.getOrPut(c) { Accumulator(i) }.add() + acc + } + .filterValues { it.count == 1 } + .minByOrNull { (_, acc) -> acc.firstIndex } + ?.value + ?.firstIndex + ?: -1 } fun main() { diff --git a/kt/iterator-for-combination.kt b/kt/iterator-for-combination.kt index 3214114..92436e3 100644 --- a/kt/iterator-for-combination.kt +++ b/kt/iterator-for-combination.kt @@ -18,8 +18,7 @@ class CombinationIterator(val characters: String, val combinationLength: Int) { // By default bumping just the last index private fun nextCombination() = nextCombination(combinationLength - 1) - private fun getCombination(): String = - indices.map { characters[it] }.joinToString(separator="") + private fun getCombination(): String = indices.map { characters[it] }.joinToString(separator = "") fun next(): String { // construct the combination @@ -35,7 +34,6 @@ class CombinationIterator(val characters: String, val combinationLength: Int) { indices.all { it < characters.length } - } /** diff --git a/kt/largest-3-same-digit-number-in-string.kt b/kt/largest-3-same-digit-number-in-string.kt index 1d4d8a0..500ded3 100644 --- a/kt/largest-3-same-digit-number-in-string.kt +++ b/kt/largest-3-same-digit-number-in-string.kt @@ -1,14 +1,15 @@ class Solution { - fun largestGoodInteger(num: String): String = num - .asSequence() - .windowed(3) - .filter { s -> - s[0] == s[1] && s[1] == s[2] - } - .map { window -> - window.joinToString("") - } - .maxByOrNull { num -> - num.toInt() - } ?: "" + fun largestGoodInteger(num: String): String = + num + .asSequence() + .windowed(3) + .filter { s -> + s[0] == s[1] && s[1] == s[2] + } + .map { window -> + window.joinToString("") + } + .maxByOrNull { num -> + num.toInt() + } ?: "" } diff --git a/kt/lowest-common-ancestor-of-a-binary-search-tree.kt b/kt/lowest-common-ancestor-of-a-binary-search-tree.kt index b999733..7525e00 100644 --- a/kt/lowest-common-ancestor-of-a-binary-search-tree.kt +++ b/kt/lowest-common-ancestor-of-a-binary-search-tree.kt @@ -7,7 +7,11 @@ */ class Solution { - fun lowestCommonAncestor(root: TreeNode?, p: TreeNode?, q: TreeNode?): TreeNode? { + fun lowestCommonAncestor( + root: TreeNode?, + p: TreeNode?, + q: TreeNode?, + ): TreeNode? { var ancestor: TreeNode? = null var pTrack = root var qTrack = root diff --git a/kt/maximize-distance-to-closest-person.kt b/kt/maximize-distance-to-closest-person.kt index 92ef3b6..c36ecbe 100644 --- a/kt/maximize-distance-to-closest-person.kt +++ b/kt/maximize-distance-to-closest-person.kt @@ -1,6 +1,5 @@ class Solution { - private fun mapSeats(seats: IntArray): MutableList = - seats.map { if (it == 1) 0 else Int.MAX_VALUE }.toMutableList() + private fun mapSeats(seats: IntArray): MutableList = seats.map { if (it == 1) 0 else Int.MAX_VALUE }.toMutableList() fun maxDistToClosest(seats: IntArray): Int { val left: MutableList = mapSeats(seats) diff --git a/kt/maximum-units-on-a-truck.kt b/kt/maximum-units-on-a-truck.kt index 7a4e46a..f84c038 100644 --- a/kt/maximum-units-on-a-truck.kt +++ b/kt/maximum-units-on-a-truck.kt @@ -1,19 +1,23 @@ class Solution { data class BoxType(val boxes: Int, val units: Int) + fun toBoxType(x: IntArray): BoxType = BoxType(x[0], x[1]) - fun maximumUnits(boxTypes: Array, truckSize: Int): Int = + fun maximumUnits( + boxTypes: Array, + truckSize: Int, + ): Int = boxTypes - .map { toBoxType(it) } - .sortedByDescending(BoxType::units) - .fold(0 to 0) { acc, boxType -> - if (acc.first < truckSize) { - val count = minOf(truckSize - acc.first, boxType.boxes) + .map { toBoxType(it) } + .sortedByDescending(BoxType::units) + .fold(0 to 0) { acc, boxType -> + if (acc.first < truckSize) { + val count = minOf(truckSize - acc.first, boxType.boxes) - (acc.first + count) to (acc.second + count * boxType.units) - } else { - acc + (acc.first + count) to (acc.second + count * boxType.units) + } else { + acc + } } - } - .second + .second } diff --git a/kt/minimum-number-of-refueling-stops.kt b/kt/minimum-number-of-refueling-stops.kt index 8d2625f..78bcf15 100644 --- a/kt/minimum-number-of-refueling-stops.kt +++ b/kt/minimum-number-of-refueling-stops.kt @@ -1,7 +1,11 @@ import java.util.PriorityQueue class Solution { - fun minRefuelStops(target: Int, startFuel: Int, stations: Array): Int { + fun minRefuelStops( + target: Int, + startFuel: Int, + stations: Array, + ): Int { var maxReach = startFuel val availableRefuelling = PriorityQueue(reverseOrder()) @@ -20,7 +24,6 @@ class Solution { return -1 } - // refuel at least once in order to progress maxReach += availableRefuelling.poll()!! refuelled++ @@ -36,8 +39,8 @@ fun main() { check(s.minRefuelStops(100, 1, arrayOf(intArrayOf(10, 100))) == -1) check( s.minRefuelStops( - 100, 10, arrayOf(intArrayOf(10, 60), intArrayOf(20, 30), intArrayOf(30, 30), intArrayOf(60, 40)) - ) == 2 + 100, 10, arrayOf(intArrayOf(10, 60), intArrayOf(20, 30), intArrayOf(30, 30), intArrayOf(60, 40)), + ) == 2, ) check( s.minRefuelStops( @@ -52,8 +55,8 @@ fun main() { intArrayOf(608, 190), intArrayOf(636, 157), intArrayOf(647, 255), - intArrayOf(841, 123) - ) - ) == 4 + intArrayOf(841, 123), + ), + ) == 4, ) } diff --git a/kt/minimum-window-substring.kt b/kt/minimum-window-substring.kt index 4a3b184..fee4147 100644 --- a/kt/minimum-window-substring.kt +++ b/kt/minimum-window-substring.kt @@ -1,5 +1,8 @@ class Solution { - fun minWindow(s: String, t: String): String { + fun minWindow( + s: String, + t: String, + ): String { val freqs = IntArray(128) { 0 } t.forEach { freqs[it.toInt()]++ diff --git a/kt/remove-nodes-from-linked-list.kt b/kt/remove-nodes-from-linked-list.kt index 41d5ded..627f718 100644 --- a/kt/remove-nodes-from-linked-list.kt +++ b/kt/remove-nodes-from-linked-list.kt @@ -19,7 +19,10 @@ fun toListNode(vararg xs: Int): ListNode? { return dummy.next } -fun linkedListEquals(head: ListNode?, xs: List): Boolean { +fun linkedListEquals( + head: ListNode?, + xs: List, +): Boolean { var node = head for ((i, x) in xs.withIndex()) { if (node == null) { diff --git a/kt/roman-to-integer.kt b/kt/roman-to-integer.kt index 1c68415..5c34567 100644 --- a/kt/roman-to-integer.kt +++ b/kt/roman-to-integer.kt @@ -2,9 +2,16 @@ class Solution { /** * Holds fixed mapping of roman numerals to their respective numeric value. */ - private val values = mapOf( - 'I' to 1, 'V' to 5, 'X' to 10, 'L' to 50, 'C' to 100, 'D' to 500, 'M' to 1000 - ) + private val values = + mapOf( + 'I' to 1, + 'V' to 5, + 'X' to 10, + 'L' to 50, + 'C' to 100, + 'D' to 500, + 'M' to 1000, + ) /** * Represents an accumulator for right fold when turning roman numeral into an integer value. @@ -16,10 +23,11 @@ class Solution { * @param it Current roman numeral digit. * @return Sign that is to be used when modifying sum of the accumulator. */ - private fun sign(it: Int): Int = when (next > it) { - true -> -1 - false -> 1 - } + private fun sign(it: Int): Int = + when (next > it) { + true -> -1 + false -> 1 + } /** * @param it Currently processed roman numeral digit. @@ -28,31 +36,33 @@ class Solution { fun update(it: Int): Accumulator = copy(sum = sum + sign(it) * it, next = it) } - fun romanToInt(s: String): Int = s - .map { values[it]!! } - .foldRight(Accumulator()) { it, acc -> - acc.update(it) - } - .sum + fun romanToInt(s: String): Int = + s + .map { values[it]!! } + .foldRight(Accumulator()) { it, acc -> + acc.update(it) + } + .sum } fun main() { val s = Solution() - val tests = mapOf( - "I" to 1, - "II" to 2, - "III" to 3, - "IV" to 4, - "V" to 5, - "VI" to 6, - "VII" to 7, - "VIII" to 8, - "IX" to 9, - "X" to 10, - "LVIII" to 58, - "MCMXCIV" to 1994 - ) + val tests = + mapOf( + "I" to 1, + "II" to 2, + "III" to 3, + "IV" to 4, + "V" to 5, + "VI" to 6, + "VII" to 7, + "VIII" to 8, + "IX" to 9, + "X" to 10, + "LVIII" to 58, + "MCMXCIV" to 1994, + ) tests.forEach { (num, i) -> check(s.romanToInt(num) == i) { diff --git a/kt/substring-with-concatenation-of-all-words.kt b/kt/substring-with-concatenation-of-all-words.kt index 640e1f0..29466c5 100644 --- a/kt/substring-with-concatenation-of-all-words.kt +++ b/kt/substring-with-concatenation-of-all-words.kt @@ -8,10 +8,16 @@ class Solution { return table } - private fun buildTable(s: String, length: Int): Map = - buildTable(s.chunked(length).asSequence()) - fun findSubstring(s: String, words: Array): List { + private fun buildTable( + s: String, + length: Int, + ): Map = buildTable(s.chunked(length).asSequence()) + + fun findSubstring( + s: String, + words: Array, + ): List { val expectedFrequencies = buildTable(words.asSequence()) val wordLen = words.first().length val windowSize = wordLen * words.size diff --git a/kt/unique-morse-code-words.kt b/kt/unique-morse-code-words.kt index e65bf97..f0aeb2b 100644 --- a/kt/unique-morse-code-words.kt +++ b/kt/unique-morse-code-words.kt @@ -1,32 +1,33 @@ class Solution { - val mapping = arrayOf( - ".-", - "-...", - "-.-.", - "-..", - ".", - "..-.", - "--.", - "....", - "..", - ".---", - "-.-", - ".-..", - "--", - "-.", - "---", - ".--.", - "--.-", - ".-.", - "...", - "-", - "..-", - "...-", - ".--", - "-..-", - "-.--", - "--.." - ) + val mapping = + arrayOf( + ".-", + "-...", + "-.-.", + "-..", + ".", + "..-.", + "--.", + "....", + "..", + ".---", + "-.-", + ".-..", + "--", + "-.", + "---", + ".--.", + "--.-", + ".-.", + "...", + "-", + "..-", + "...-", + ".--", + "-..-", + "-.--", + "--..", + ) private fun charToMorse(c: Char): String = mapping[c - 'a'] diff --git a/kt/validate-binary-search-tree.kt b/kt/validate-binary-search-tree.kt index 9b9058d..ed85d17 100644 --- a/kt/validate-binary-search-tree.kt +++ b/kt/validate-binary-search-tree.kt @@ -10,16 +10,19 @@ */ class Solution { private data class SpecialRange(val min: Int? = null, val max: Int? = null) { - fun check(x: Int): Boolean = - (min == null || x > min) && (max == null || x < max) + fun check(x: Int): Boolean = (min == null || x > min) && (max == null || x < max) } - private fun isValidBST(root: TreeNode?, range: SpecialRange): Boolean = + private fun isValidBST( + root: TreeNode?, + range: SpecialRange, + ): Boolean = when (root) { null -> true - else -> range.check(root.`val`) - && isValidBST(root.left, range.copy(max=root.`val`)) - && isValidBST(root.right, range.copy(min=root.`val`)) + else -> + range.check(root.`val`) && + isValidBST(root.left, range.copy(max = root.`val`)) && + isValidBST(root.right, range.copy(min = root.`val`)) } fun isValidBST(root: TreeNode?): Boolean = isValidBST(root, SpecialRange()) diff --git a/kt/word-ladder-ii.kt b/kt/word-ladder-ii.kt index ba22903..ab6b121 100644 --- a/kt/word-ladder-ii.kt +++ b/kt/word-ladder-ii.kt @@ -1,12 +1,18 @@ class Solution { - private fun wordDifference(lhs: String, rhs: String): Int = lhs.zip(rhs).count { (l, r) -> l != r } + private fun wordDifference( + lhs: String, + rhs: String, + ): Int = lhs.zip(rhs).count { (l, r) -> l != r } private enum class VertexState { - Unvisited, Enqueued, Done + Unvisited, + Enqueued, + Done, } private data class Vertex( - val label: T, val neighbours: MutableSet> = mutableSetOf() + val label: T, + val neighbours: MutableSet> = mutableSetOf(), ) { var distance: Int = Int.MAX_VALUE val parents: MutableSet> = mutableSetOf() @@ -22,15 +28,18 @@ class Solution { } fun transition() { - state = when (state) { - VertexState.Unvisited -> VertexState.Enqueued - VertexState.Enqueued -> VertexState.Done - VertexState.Done -> error("Cannot transition further!") - } + state = + when (state) { + VertexState.Unvisited -> VertexState.Enqueued + VertexState.Enqueued -> VertexState.Done + VertexState.Done -> error("Cannot transition further!") + } } override fun hashCode(): Int = label.hashCode() + override fun toString(): String = "$label(${neighbours.map { it.label.toString() }})" + override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false @@ -46,19 +55,28 @@ class Solution { private class Graph { private val vertices: MutableMap> = mutableMapOf() - fun addVertex(src: T, dst: T) { + fun addVertex( + src: T, + dst: T, + ) { val u = vertices.getOrPut(src) { Vertex(src) } val v = vertices.getOrPut(dst) { Vertex(dst) } u.add(v) } - fun addSymmetricVertex(src: T, dst: T) { + fun addSymmetricVertex( + src: T, + dst: T, + ) { addVertex(src, dst) addVertex(dst, src) } - private fun processVertex(queue: ArrayDeque>, u: Vertex) { + private fun processVertex( + queue: ArrayDeque>, + u: Vertex, + ) { u.neighbours.forEach { v -> if (v.state == VertexState.Unvisited) { queue.addLast(v) @@ -75,7 +93,10 @@ class Solution { u.transition() } - fun bfs(src: T, dst: T) { + fun bfs( + src: T, + dst: T, + ) { if (vertices[src] == null) { return } @@ -101,7 +122,10 @@ class Solution { override fun toString(): String = vertices.toString() } - private fun constructGraph(src: String, vertices: List): Graph { + private fun constructGraph( + src: String, + vertices: List, + ): Graph { val g = Graph() vertices @@ -118,7 +142,9 @@ class Solution { } private fun constructPath( - graph: Graph, currentPath: MutableList, paths: MutableList> + graph: Graph, + currentPath: MutableList, + paths: MutableList>, ): MutableList> { if (graph.parents(currentPath.last()).isEmpty()) { paths.add(currentPath.reversed().toMutableList()) @@ -135,7 +161,9 @@ class Solution { } fun findLadders( - beginWord: String, endWord: String, wordList: List + beginWord: String, + endWord: String, + wordList: List, ): List> { val graph = constructGraph(beginWord, wordList) graph.bfs(beginWord, endWord) @@ -147,9 +175,10 @@ fun main() { val s = Solution() check( - s.findLadders("hit", "cog", listOf("hot", "dot", "dog", "lot", "log", "cog")) == listOf( - listOf("hit", "hot", "dot", "dog", "cog"), listOf("hit", "hot", "lot", "log", "cog") - ) + s.findLadders("hit", "cog", listOf("hot", "dot", "dog", "lot", "log", "cog")) == + listOf( + listOf("hit", "hot", "dot", "dog", "cog"), listOf("hit", "hot", "lot", "log", "cog"), + ), ) check(s.findLadders("hit", "cog", listOf("hot", "dot", "dog", "lot", "log")) == emptyList>()) check(s.findLadders("hot", "dog", listOf("hot", "dog")) == emptyList>())