style(kt): reformat the files

Signed-off-by: Matej Focko <me@mfocko.xyz>
This commit is contained in:
Matej Focko 2024-05-17 18:23:38 +02:00
parent 1eab058c56
commit aaaebf1d52
Signed by: mfocko
GPG key ID: 7C47D46246790496
19 changed files with 211 additions and 140 deletions

View file

@ -9,7 +9,10 @@
* } * }
*/ */
class Solution { class Solution {
fun inorderTraversal(root: TreeNode?, values: MutableList<Int>): List<Int> { fun inorderTraversal(
root: TreeNode?,
values: MutableList<Int>,
): List<Int> {
if (root == null) { if (root == null) {
return values return values
} }
@ -21,6 +24,5 @@ class Solution {
return values return values
} }
fun inorderTraversal(root: TreeNode?): List<Int> fun inorderTraversal(root: TreeNode?): List<Int> = inorderTraversal(root, mutableListOf<Int>())
= inorderTraversal(root, mutableListOf<Int>())
} }

View file

@ -9,7 +9,11 @@
* } * }
*/ */
class Solution { class Solution {
private fun levelOrder(root: TreeNode?, levels: MutableList<MutableList<Int>>, level: Int): MutableList<MutableList<Int>> { private fun levelOrder(
root: TreeNode?,
levels: MutableList<MutableList<Int>>,
level: Int,
): MutableList<MutableList<Int>> {
if (root == null) { if (root == null) {
return levels return levels
} }

View file

@ -3,11 +3,9 @@ class Solution {
val n = matrix.size val n = matrix.size
val required = (1..n).toSet() val required = (1..n).toSet()
fun checkDimension( fun checkDimension(dimensions: Iterable<Iterable<Int>>): Boolean = dimensions.all { it.toSet() == required }
dimensions: Iterable<Iterable<Int>>
): Boolean = dimensions.all { it.toSet() == required }
return checkDimension(matrix.map(IntArray::toList)) && 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] } })
} }
} }

View file

@ -18,7 +18,6 @@ class Solution {
val left = "(${tree2str(root.left)})" val left = "(${tree2str(root.left)})"
val right = "(${tree2str(root.right)})" val right = "(${tree2str(root.right)})"
if (left == "()" && right == "()") { if (left == "()" && right == "()") {
return value return value
} else if (right == "()") { } else if (right == "()") {

View file

@ -19,7 +19,10 @@ fun toListNode(vararg xs: Int): ListNode? {
return dummy.next return dummy.next
} }
fun linkedListEquals(head: ListNode?, xs: List<Int>): Boolean { fun linkedListEquals(
head: ListNode?,
xs: List<Int>,
): Boolean {
var node = head var node = head
for ((i, x) in xs.withIndex()) { for ((i, x) in xs.withIndex()) {
if (node == null) { if (node == null) {

View file

@ -5,7 +5,8 @@ class Solution {
} }
} }
fun firstUniqChar(s: String): Int = s fun firstUniqChar(s: String): Int =
s
.foldIndexed(mutableMapOf<Char, Accumulator>()) { i, acc, c -> .foldIndexed(mutableMapOf<Char, Accumulator>()) { i, acc, c ->
acc.getOrPut(c) { Accumulator(i) }.add() acc.getOrPut(c) { Accumulator(i) }.add()
acc acc

View file

@ -18,8 +18,7 @@ class CombinationIterator(val characters: String, val combinationLength: Int) {
// By default bumping just the last index // By default bumping just the last index
private fun nextCombination() = nextCombination(combinationLength - 1) private fun nextCombination() = nextCombination(combinationLength - 1)
private fun getCombination(): String = private fun getCombination(): String = indices.map { characters[it] }.joinToString(separator = "")
indices.map { characters[it] }.joinToString(separator="")
fun next(): String { fun next(): String {
// construct the combination // construct the combination
@ -35,7 +34,6 @@ class CombinationIterator(val characters: String, val combinationLength: Int) {
indices.all { indices.all {
it < characters.length it < characters.length
} }
} }
/** /**

View file

@ -1,5 +1,6 @@
class Solution { class Solution {
fun largestGoodInteger(num: String): String = num fun largestGoodInteger(num: String): String =
num
.asSequence() .asSequence()
.windowed(3) .windowed(3)
.filter { s -> .filter { s ->

View file

@ -7,7 +7,11 @@
*/ */
class Solution { 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 ancestor: TreeNode? = null
var pTrack = root var pTrack = root
var qTrack = root var qTrack = root

View file

@ -1,6 +1,5 @@
class Solution { class Solution {
private fun mapSeats(seats: IntArray): MutableList<Int> = private fun mapSeats(seats: IntArray): MutableList<Int> = seats.map { if (it == 1) 0 else Int.MAX_VALUE }.toMutableList()
seats.map { if (it == 1) 0 else Int.MAX_VALUE }.toMutableList()
fun maxDistToClosest(seats: IntArray): Int { fun maxDistToClosest(seats: IntArray): Int {
val left: MutableList<Int> = mapSeats(seats) val left: MutableList<Int> = mapSeats(seats)

View file

@ -1,8 +1,12 @@
class Solution { class Solution {
data class BoxType(val boxes: Int, val units: Int) data class BoxType(val boxes: Int, val units: Int)
fun toBoxType(x: IntArray): BoxType = BoxType(x[0], x[1]) fun toBoxType(x: IntArray): BoxType = BoxType(x[0], x[1])
fun maximumUnits(boxTypes: Array<IntArray>, truckSize: Int): Int = fun maximumUnits(
boxTypes: Array<IntArray>,
truckSize: Int,
): Int =
boxTypes boxTypes
.map { toBoxType(it) } .map { toBoxType(it) }
.sortedByDescending(BoxType::units) .sortedByDescending(BoxType::units)

View file

@ -1,7 +1,11 @@
import java.util.PriorityQueue import java.util.PriorityQueue
class Solution { class Solution {
fun minRefuelStops(target: Int, startFuel: Int, stations: Array<IntArray>): Int { fun minRefuelStops(
target: Int,
startFuel: Int,
stations: Array<IntArray>,
): Int {
var maxReach = startFuel var maxReach = startFuel
val availableRefuelling = PriorityQueue<Int>(reverseOrder()) val availableRefuelling = PriorityQueue<Int>(reverseOrder())
@ -20,7 +24,6 @@ class Solution {
return -1 return -1
} }
// refuel at least once in order to progress // refuel at least once in order to progress
maxReach += availableRefuelling.poll()!! maxReach += availableRefuelling.poll()!!
refuelled++ refuelled++
@ -36,8 +39,8 @@ fun main() {
check(s.minRefuelStops(100, 1, arrayOf(intArrayOf(10, 100))) == -1) check(s.minRefuelStops(100, 1, arrayOf(intArrayOf(10, 100))) == -1)
check( check(
s.minRefuelStops( s.minRefuelStops(
100, 10, arrayOf(intArrayOf(10, 60), intArrayOf(20, 30), intArrayOf(30, 30), intArrayOf(60, 40)) 100, 10, arrayOf(intArrayOf(10, 60), intArrayOf(20, 30), intArrayOf(30, 30), intArrayOf(60, 40)),
) == 2 ) == 2,
) )
check( check(
s.minRefuelStops( s.minRefuelStops(
@ -52,8 +55,8 @@ fun main() {
intArrayOf(608, 190), intArrayOf(608, 190),
intArrayOf(636, 157), intArrayOf(636, 157),
intArrayOf(647, 255), intArrayOf(647, 255),
intArrayOf(841, 123) intArrayOf(841, 123),
) ),
) == 4 ) == 4,
) )
} }

View file

@ -1,5 +1,8 @@
class Solution { class Solution {
fun minWindow(s: String, t: String): String { fun minWindow(
s: String,
t: String,
): String {
val freqs = IntArray(128) { 0 } val freqs = IntArray(128) { 0 }
t.forEach { t.forEach {
freqs[it.toInt()]++ freqs[it.toInt()]++

View file

@ -19,7 +19,10 @@ fun toListNode(vararg xs: Int): ListNode? {
return dummy.next return dummy.next
} }
fun linkedListEquals(head: ListNode?, xs: List<Int>): Boolean { fun linkedListEquals(
head: ListNode?,
xs: List<Int>,
): Boolean {
var node = head var node = head
for ((i, x) in xs.withIndex()) { for ((i, x) in xs.withIndex()) {
if (node == null) { if (node == null) {

View file

@ -2,8 +2,15 @@ class Solution {
/** /**
* Holds fixed mapping of roman numerals to their respective numeric value. * Holds fixed mapping of roman numerals to their respective numeric value.
*/ */
private val values = mapOf( private val values =
'I' to 1, 'V' to 5, 'X' to 10, 'L' to 50, 'C' to 100, 'D' to 500, 'M' to 1000 mapOf(
'I' to 1,
'V' to 5,
'X' to 10,
'L' to 50,
'C' to 100,
'D' to 500,
'M' to 1000,
) )
/** /**
@ -16,7 +23,8 @@ class Solution {
* @param it Current roman numeral digit. * @param it Current roman numeral digit.
* @return Sign that is to be used when modifying sum of the accumulator. * @return Sign that is to be used when modifying sum of the accumulator.
*/ */
private fun sign(it: Int): Int = when (next > it) { private fun sign(it: Int): Int =
when (next > it) {
true -> -1 true -> -1
false -> 1 false -> 1
} }
@ -28,7 +36,8 @@ class Solution {
fun update(it: Int): Accumulator = copy(sum = sum + sign(it) * it, next = it) fun update(it: Int): Accumulator = copy(sum = sum + sign(it) * it, next = it)
} }
fun romanToInt(s: String): Int = s fun romanToInt(s: String): Int =
s
.map { values[it]!! } .map { values[it]!! }
.foldRight(Accumulator()) { it, acc -> .foldRight(Accumulator()) { it, acc ->
acc.update(it) acc.update(it)
@ -39,7 +48,8 @@ class Solution {
fun main() { fun main() {
val s = Solution() val s = Solution()
val tests = mapOf( val tests =
mapOf(
"I" to 1, "I" to 1,
"II" to 2, "II" to 2,
"III" to 3, "III" to 3,
@ -51,7 +61,7 @@ fun main() {
"IX" to 9, "IX" to 9,
"X" to 10, "X" to 10,
"LVIII" to 58, "LVIII" to 58,
"MCMXCIV" to 1994 "MCMXCIV" to 1994,
) )
tests.forEach { (num, i) -> tests.forEach { (num, i) ->

View file

@ -8,10 +8,16 @@ class Solution {
return table return table
} }
private fun buildTable(s: String, length: Int): Map<String, Int> =
buildTable(s.chunked(length).asSequence())
fun findSubstring(s: String, words: Array<String>): List<Int> { private fun buildTable(
s: String,
length: Int,
): Map<String, Int> = buildTable(s.chunked(length).asSequence())
fun findSubstring(
s: String,
words: Array<String>,
): List<Int> {
val expectedFrequencies = buildTable(words.asSequence()) val expectedFrequencies = buildTable(words.asSequence())
val wordLen = words.first().length val wordLen = words.first().length
val windowSize = wordLen * words.size val windowSize = wordLen * words.size

View file

@ -1,5 +1,6 @@
class Solution { class Solution {
val mapping = arrayOf( val mapping =
arrayOf(
".-", ".-",
"-...", "-...",
"-.-.", "-.-.",
@ -25,7 +26,7 @@ class Solution {
".--", ".--",
"-..-", "-..-",
"-.--", "-.--",
"--.." "--..",
) )
private fun charToMorse(c: Char): String = mapping[c - 'a'] private fun charToMorse(c: Char): String = mapping[c - 'a']

View file

@ -10,16 +10,19 @@
*/ */
class Solution { class Solution {
private data class SpecialRange(val min: Int? = null, val max: Int? = null) { private data class SpecialRange(val min: Int? = null, val max: Int? = null) {
fun check(x: Int): Boolean = fun check(x: Int): Boolean = (min == null || x > min) && (max == null || x < max)
(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) { when (root) {
null -> true null -> true
else -> range.check(root.`val`) else ->
&& isValidBST(root.left, range.copy(max=root.`val`)) range.check(root.`val`) &&
&& isValidBST(root.right, range.copy(min=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()) fun isValidBST(root: TreeNode?): Boolean = isValidBST(root, SpecialRange())

View file

@ -1,12 +1,18 @@
class Solution { 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 { private enum class VertexState {
Unvisited, Enqueued, Done Unvisited,
Enqueued,
Done,
} }
private data class Vertex<T>( private data class Vertex<T>(
val label: T, val neighbours: MutableSet<Vertex<T>> = mutableSetOf() val label: T,
val neighbours: MutableSet<Vertex<T>> = mutableSetOf(),
) { ) {
var distance: Int = Int.MAX_VALUE var distance: Int = Int.MAX_VALUE
val parents: MutableSet<Vertex<T>> = mutableSetOf() val parents: MutableSet<Vertex<T>> = mutableSetOf()
@ -22,7 +28,8 @@ class Solution {
} }
fun transition() { fun transition() {
state = when (state) { state =
when (state) {
VertexState.Unvisited -> VertexState.Enqueued VertexState.Unvisited -> VertexState.Enqueued
VertexState.Enqueued -> VertexState.Done VertexState.Enqueued -> VertexState.Done
VertexState.Done -> error("Cannot transition further!") VertexState.Done -> error("Cannot transition further!")
@ -30,7 +37,9 @@ class Solution {
} }
override fun hashCode(): Int = label.hashCode() override fun hashCode(): Int = label.hashCode()
override fun toString(): String = "$label(${neighbours.map { it.label.toString() }})" override fun toString(): String = "$label(${neighbours.map { it.label.toString() }})"
override fun equals(other: Any?): Boolean { override fun equals(other: Any?): Boolean {
if (this === other) return true if (this === other) return true
if (javaClass != other?.javaClass) return false if (javaClass != other?.javaClass) return false
@ -46,19 +55,28 @@ class Solution {
private class Graph<T> { private class Graph<T> {
private val vertices: MutableMap<T, Vertex<T>> = mutableMapOf() private val vertices: MutableMap<T, Vertex<T>> = mutableMapOf()
fun addVertex(src: T, dst: T) { fun addVertex(
src: T,
dst: T,
) {
val u = vertices.getOrPut(src) { Vertex(src) } val u = vertices.getOrPut(src) { Vertex(src) }
val v = vertices.getOrPut(dst) { Vertex(dst) } val v = vertices.getOrPut(dst) { Vertex(dst) }
u.add(v) u.add(v)
} }
fun addSymmetricVertex(src: T, dst: T) { fun addSymmetricVertex(
src: T,
dst: T,
) {
addVertex(src, dst) addVertex(src, dst)
addVertex(dst, src) addVertex(dst, src)
} }
private fun processVertex(queue: ArrayDeque<Vertex<T>>, u: Vertex<T>) { private fun processVertex(
queue: ArrayDeque<Vertex<T>>,
u: Vertex<T>,
) {
u.neighbours.forEach { v -> u.neighbours.forEach { v ->
if (v.state == VertexState.Unvisited) { if (v.state == VertexState.Unvisited) {
queue.addLast(v) queue.addLast(v)
@ -75,7 +93,10 @@ class Solution {
u.transition() u.transition()
} }
fun bfs(src: T, dst: T) { fun bfs(
src: T,
dst: T,
) {
if (vertices[src] == null) { if (vertices[src] == null) {
return return
} }
@ -101,7 +122,10 @@ class Solution {
override fun toString(): String = vertices.toString() override fun toString(): String = vertices.toString()
} }
private fun constructGraph(src: String, vertices: List<String>): Graph<String> { private fun constructGraph(
src: String,
vertices: List<String>,
): Graph<String> {
val g = Graph<String>() val g = Graph<String>()
vertices vertices
@ -118,7 +142,9 @@ class Solution {
} }
private fun constructPath( private fun constructPath(
graph: Graph<String>, currentPath: MutableList<String>, paths: MutableList<MutableList<String>> graph: Graph<String>,
currentPath: MutableList<String>,
paths: MutableList<MutableList<String>>,
): MutableList<MutableList<String>> { ): MutableList<MutableList<String>> {
if (graph.parents(currentPath.last()).isEmpty()) { if (graph.parents(currentPath.last()).isEmpty()) {
paths.add(currentPath.reversed().toMutableList()) paths.add(currentPath.reversed().toMutableList())
@ -135,7 +161,9 @@ class Solution {
} }
fun findLadders( fun findLadders(
beginWord: String, endWord: String, wordList: List<String> beginWord: String,
endWord: String,
wordList: List<String>,
): List<List<String>> { ): List<List<String>> {
val graph = constructGraph(beginWord, wordList) val graph = constructGraph(beginWord, wordList)
graph.bfs(beginWord, endWord) graph.bfs(beginWord, endWord)
@ -147,9 +175,10 @@ fun main() {
val s = Solution() val s = Solution()
check( check(
s.findLadders("hit", "cog", listOf("hot", "dot", "dog", "lot", "log", "cog")) == listOf( s.findLadders("hit", "cog", listOf("hot", "dot", "dog", "lot", "log", "cog")) ==
listOf("hit", "hot", "dot", "dog", "cog"), listOf("hit", "hot", "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<List<String>>()) check(s.findLadders("hit", "cog", listOf("hot", "dot", "dog", "lot", "log")) == emptyList<List<String>>())
check(s.findLadders("hot", "dog", listOf("hot", "dog")) == emptyList<List<String>>()) check(s.findLadders("hot", "dog", listOf("hot", "dog")) == emptyList<List<String>>())