Skip to content

Instantly share code, notes, and snippets.

View UNISERVO1's full-sized avatar

Marcus Young UNISERVO1

View GitHub Profile
@UNISERVO1
UNISERVO1 / find_all_array_dups_using_negs.kt
Created August 7, 2020 04:14
August LeetCoding Challenge Week 1: Day 6 (using negative substitution for O(n))
import kotlin.math.abs
class Solution {
fun findDuplicates(nums: IntArray): List<Int> {
fun twiceFound(acc: Pair<List<Int>, MutableList<Int>>, num: Int): Pair<List<Int>, MutableList<Int>> {
val (uniques, negs) = acc
return if (negs[abs(num) - 1] < 0) {
uniques.plus(num) to negs
} else {
negs[abs(num) - 1] = -1 * negs[abs(num) - 1]
@UNISERVO1
UNISERVO1 / find_all_array_dups.kt
Created August 6, 2020 22:22
August LeetCoding Challenge Week 1: Day 6
class Solution {
fun findDuplicates(nums: IntArray): List<Int> {
fun twiceFound(uniques: MutableMap<Int, Int>, num: Int): MutableMap<Int, Int> {
uniques.set(num, uniques.getOrPut(num){ 0 } + 1)
return uniques
}
return nums.fold(mutableMapOf<Int, Int>(), { t, num -> twiceFound(t, num) }).toMap().filterValues{ it == 2 }.keys.toList()
}
@UNISERVO1
UNISERVO1 / power_of_four.kt
Created August 4, 2020 23:06
August LeetCoding Challenge Week 1: Day 4
class Solution {
val mask: Int = (0..31 step 2).fold(0){ acc, v -> acc + (1 shl v)}
fun isPowerOfFour(num: Int): Boolean {
return (num - 1) and num == 0 && (mask and num) > 0
}
}
@UNISERVO1
UNISERVO1 / is_palindrome.kt
Last active August 4, 2020 02:14
August LeetCoding Challenge Week 1: Day 3
class Solution {
fun isPalindrome(s: String): Boolean {
val targetString: String = s.filter{ it.isLetterOrDigit() }.toLowerCase()
return targetString == targetString.reversed()
}
}
@UNISERVO1
UNISERVO1 / my_hash_set.kt
Last active August 3, 2020 11:58
August LeetCoding Challenge Week 1: Day 2
class MyHashSet() {
val numBuckets: Int = 97
val buckets = List<MutableSet<Int>>(numBuckets){ mutableSetOf<Int>() }
val hashFunc : (Int) -> Int = { key: Int -> key % numBuckets }
fun add(key: Int) {
buckets.get(hashFunc(key)).add(key)
}
@UNISERVO1
UNISERVO1 / detect_capital.kt
Last active August 3, 2020 11:57
August LeetCoding Challenge Week 1: Day 1
class Solution {
fun detectCapitalUse(word: String): Boolean {
return word.all{ it.isLowerCase() } ||
word.all{ it.isUpperCase() } ||
(word.first().isUpperCase() && word.drop(1).all{ it.isLowerCase() })
}
}