├── .gitignore
├── .idea
├── codeStyles
│ ├── Project.xml
│ └── codeStyleConfig.xml
├── dictionaries
│ └── FABBI.xml
├── inspectionProfiles
│ └── Project_Default.xml
├── kotlinc.xml
├── leetcode
│ └── editor.xml
├── libraries
│ ├── KotlinJavaRuntime.xml
│ └── jetbrains_kotlinx_coroutines_core.xml
├── misc.xml
├── modules.xml
├── uiDesigner.xml
├── vcs.xml
└── workspace.xml
├── LICENSE
├── Readme.md
├── data-structures-and-algorithms-kotlin.iml
├── lib
├── apiguardian-api-1.1.0.jar
├── junit-jupiter-5.7.0.jar
├── junit-jupiter-api-5.7.0.jar
├── junit-jupiter-engine-5.7.0.jar
├── junit-jupiter-params-5.7.0.jar
├── junit-platform-commons-1.7.0.jar
├── junit-platform-engine-1.7.0.jar
└── opentest4j-1.2.0.jar
└── src
├── algorithms
├── bit_manipulation
│ ├── BitManipulation.kt
│ └── RangeBitWiseAnd.kt
├── recursive
│ ├── BinarySearchRecursive.kt
│ └── LongestPalindromic.kt
├── search
│ ├── BinarySearch.kt
│ ├── InterpolationSearch.kt
│ ├── LinearSearch.kt
│ └── TernarySearch.kt
├── sliding_window
│ ├── MaximumOfValue.kt
│ └── lengthOfLongestSubstring.kt
├── sorting
│ ├── BubbleSort.kt
│ ├── InsertionSort.kt
│ ├── MergeSort.kt
│ ├── QuickSort.kt
│ └── SelectionSort.kt
└── twopointer
│ └── ThreeSum.kt
├── codility
├── BinaryGap.kt
├── Bracket.kt
├── CyclicRotation.kt
├── FibonacciCodility.kt
├── FirstMissingPositive.kt
├── FirstUniqueNumber.kt
├── Fish.kt
├── FrogRiverOne.kt
├── MaxCounters.kt
├── NailingFlanks.kt
├── NumberOfDiscIntersections.kt
├── NumberSolitaire.kt
├── OddOccurrencesInArray.kt
└── StoneWall.kt
├── data_structure
├── graph
│ └── Graph.kt
├── linkedlist
│ ├── DoublyLinkedList.kt
│ └── SinglyLinkedList.kt
├── queue
│ ├── QueueUsingStack.kt
│ └── QueuesUsingLinkedList.kt
├── stack
│ ├── MinStack.kt
│ └── StackUsingLinkedList.kt
├── string
│ ├── ReverseString.kt
│ └── numberOfMatching.kt
├── tree
│ ├── BinaryTree.kt
│ ├── GraphBFS.kt
│ ├── InsertionTree.kt
│ ├── TreeBFS.kt
│ └── TreeTraversal.kt
└── trie
│ └── Trie.kt
├── dynamicprogramming
├── ClimbingStairs.kt
├── EditDistance.kt
├── Fibonacci.kt
├── LongestIncreasingSubsequence.kt
├── LongestValidParenthesis.kt
├── MinimumPathSum.kt
├── NewStoneGame.kt
├── PascalTriAngel.kt
├── RobberHouse.kt
└── UniquePath.kt
├── hackerrank
└── ThePowerOfSum.kt
├── leetcodeProblem
└── leetcode
│ └── editor
│ └── en
│ ├── BestTimeToBuyAndSellStockIi.kt
│ ├── BestTimeToBuyAndSellStockWithTransactionFee.kt
│ ├── BinaryTreeInorderTraversal.kt
│ ├── BullsAndCows.kt
│ ├── ContainsDuplicate.kt
│ ├── CountAndSay.kt
│ ├── DecodeWays.kt
│ ├── FindAllNumbersDisappearedInAnArray.kt
│ ├── FindFirstAndLastPositionOfElementInSortedArray.kt
│ ├── FindMinimumInRotatedSortedArray.kt
│ ├── FindTheWinnerOfTheCircularGame.kt
│ ├── HammingDistance.kt
│ ├── InsertDeleteGetrandomO1.kt
│ ├── IntersectionOfTwoLinkedLists.kt
│ ├── IteratorForCombination.kt
│ ├── LargestDivisibleSubset.kt
│ ├── LongestIncreasingSubsequence.kt
│ ├── LongestSubstringWithoutRepeatingCharacters.kt
│ ├── MaximumSubarray.kt
│ ├── MergeSortedArray.kt
│ ├── MinStack.kt
│ ├── MinimumRemoveToMakeValidParentheses.kt
│ ├── MinimumValueToGetPositiveStepByStepSum.kt
│ ├── MinimumWindowSubstring.kt
│ ├── MissingNumber.kt
│ ├── MoveZeroes.kt
│ ├── MultiplyStrings.kt
│ ├── NextGreaterElementI.kt
│ ├── NumberOfValidWordsForEachPuzzle.kt
│ ├── PascalsTriangle.kt
│ ├── RankTeamsByVotes.kt
│ ├── RansomNote.kt
│ ├── RemoveDuplicatesFromSortedListIi.kt
│ ├── RemoveLinkedListElements.kt
│ ├── RemoveNthNodeFromEndOfList.kt
│ ├── ReorderList.kt
│ ├── ReplaceWords.kt
│ ├── ReshapeTheMatrix.kt
│ ├── ReverseLinkedList.kt
│ ├── ReverseString.kt
│ ├── ReverseWordsInAStringIii.kt
│ ├── RotateArray.kt
│ ├── RussianDollEnvelopes.kt
│ ├── SearchA2dMatrix.kt
│ ├── SearchInRotatedSortedArray.kt
│ ├── SetMatrixZeroes.kt
│ ├── SingleNumberIii.kt
│ ├── StringWithoutAaaOrBbb.kt
│ ├── SubtreeOfAnotherTree.kt
│ ├── SumOfBeautyInTheArray.kt
│ ├── SwapNodesInPairs.kt
│ ├── ThreeSum.kt
│ ├── TwoSum.kt
│ ├── TwoSumIiInputArrayIsSorted.kt
│ ├── UniqueBinarySearchTrees.kt
│ ├── ValidSudoku.kt
│ ├── WordSearch.kt
│ └── WordSearchIi.kt
├── leetcode_daily_chalange
├── BestTimeToBuyAndSellStock3.kt
├── BestTimeToBuyAndSellStockWithCoolDown.kt
├── DiameterOfBinaryTree.kt
├── FindAllDuplicatesinanArray.kt
├── InsertDeleteGetrandomO1.kt
├── LongestSumDivisibleByK.kt
├── RangeBitWiseAnd.kt
├── WordSearch.kt
└── WordSearch2.kt
├── leetcode_study_badge
├── algorithm
│ ├── Day1.kt
│ ├── Day11.kt
│ ├── Day2.kt
│ ├── Day3.kt
│ ├── Day4.kt
│ ├── Day5.kt
│ ├── Day6.kt
│ └── Day7.kt
├── data_structure
│ ├── Day1.kt
│ ├── Day15.kt
│ ├── Day16.kt
│ ├── Day17.kt
│ ├── Day18.kt
│ ├── Day19.kt
│ ├── Day2.kt
│ ├── Day20.kt
│ ├── Day21.kt
│ ├── Day3.kt
│ ├── Day4.kt
│ ├── Day5.kt
│ ├── Day6.kt
│ ├── Day7.kt
│ ├── Day8.kt
│ └── Day91011121314.kt
└── dynamic_programming
│ ├── Day1.kt
│ ├── Day2.kt
│ ├── Day3.kt
│ ├── Day4.kt
│ ├── Day5.kt
│ └── Day6.kt
└── solid_principle
├── DependencyInversion.kt
├── InterfaceSegregation.kt
├── LiskovSubstitution.kt
├── OpenClose.kt
└── SingleResponsibility.kt
/.gitignore:
--------------------------------------------------------------------------------
1 | /out/
2 | /src/leetcodeProblem/leetcode/editor/en/doc
3 | /src/privatePackage
4 | /src/algorithms/Interview.kt
5 | /src/codility/CodilityChallanges.kt
6 | /lib
--------------------------------------------------------------------------------
/.idea/codeStyles/Project.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.idea/codeStyles/codeStyleConfig.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
--------------------------------------------------------------------------------
/.idea/dictionaries/FABBI.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 | challanges
5 | codility
6 | piala
7 | pipot
8 | subseq
9 | variabel
10 |
11 |
12 |
--------------------------------------------------------------------------------
/.idea/inspectionProfiles/Project_Default.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
--------------------------------------------------------------------------------
/.idea/kotlinc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/libraries/KotlinJavaRuntime.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
--------------------------------------------------------------------------------
/.idea/libraries/jetbrains_kotlinx_coroutines_core.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
--------------------------------------------------------------------------------
/.idea/misc.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/.idea/modules.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
--------------------------------------------------------------------------------
/.idea/vcs.xml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2021 Fani Abdullah
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/data-structures-and-algorithms-kotlin.iml:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 |
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
--------------------------------------------------------------------------------
/lib/apiguardian-api-1.1.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/faniabdullah/dsa-kotlin/ecf14fe132824e944818fda1123f1c7796c30532/lib/apiguardian-api-1.1.0.jar
--------------------------------------------------------------------------------
/lib/junit-jupiter-5.7.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/faniabdullah/dsa-kotlin/ecf14fe132824e944818fda1123f1c7796c30532/lib/junit-jupiter-5.7.0.jar
--------------------------------------------------------------------------------
/lib/junit-jupiter-api-5.7.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/faniabdullah/dsa-kotlin/ecf14fe132824e944818fda1123f1c7796c30532/lib/junit-jupiter-api-5.7.0.jar
--------------------------------------------------------------------------------
/lib/junit-jupiter-engine-5.7.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/faniabdullah/dsa-kotlin/ecf14fe132824e944818fda1123f1c7796c30532/lib/junit-jupiter-engine-5.7.0.jar
--------------------------------------------------------------------------------
/lib/junit-jupiter-params-5.7.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/faniabdullah/dsa-kotlin/ecf14fe132824e944818fda1123f1c7796c30532/lib/junit-jupiter-params-5.7.0.jar
--------------------------------------------------------------------------------
/lib/junit-platform-commons-1.7.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/faniabdullah/dsa-kotlin/ecf14fe132824e944818fda1123f1c7796c30532/lib/junit-platform-commons-1.7.0.jar
--------------------------------------------------------------------------------
/lib/junit-platform-engine-1.7.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/faniabdullah/dsa-kotlin/ecf14fe132824e944818fda1123f1c7796c30532/lib/junit-platform-engine-1.7.0.jar
--------------------------------------------------------------------------------
/lib/opentest4j-1.2.0.jar:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/faniabdullah/dsa-kotlin/ecf14fe132824e944818fda1123f1c7796c30532/lib/opentest4j-1.2.0.jar
--------------------------------------------------------------------------------
/src/algorithms/bit_manipulation/BitManipulation.kt:
--------------------------------------------------------------------------------
1 | package algorithms.bit_manipulation
2 |
3 | fun main() {
4 | // https://www.programiz.com/kotlin-programming/bitwise
5 | println(5 or 3)
6 | println(5 and 9)
7 | println(7 xor 7)
8 | }
--------------------------------------------------------------------------------
/src/algorithms/bit_manipulation/RangeBitWiseAnd.kt:
--------------------------------------------------------------------------------
1 | package algorithms.bit_manipulation
2 |
3 | class RangeBitWiseAnd {
4 | fun rangeBitwiseAnd(left: Int, right: Int): Int {
5 | if (right == left) return left
6 |
7 | var n = right - left
8 |
9 | n = n or (n ushr 1)
10 | n = n or (n ushr 2)
11 | n = n or (n ushr 4)
12 | n = n or (n ushr 8)
13 | n = n or (n ushr 16)
14 |
15 | n = (n + 1)
16 | n = n ushr 1
17 | if (n < 0) return 0
18 |
19 | n = (n or (n - 1)).inv()
20 |
21 | return n and right and left
22 | }
23 | }
--------------------------------------------------------------------------------
/src/algorithms/recursive/BinarySearchRecursive.kt:
--------------------------------------------------------------------------------
1 | package algorithms.recursive
2 |
3 | class BinarySearchRecursive {
4 | fun binarySearch(
5 | intArray: IntArray, first: Int,
6 | last: Int, target: Int
7 | ): Int {
8 | if (last >= first) {
9 | val mid: Int = first + (last - first) / 2
10 | if (intArray[mid] == target) return mid
11 | if (intArray[mid] > target) return binarySearch(intArray, first, mid - 1, target)
12 | return binarySearch(intArray, mid + 1, last, target)
13 | }
14 |
15 | return -1
16 | }
17 | }
18 |
19 | fun main() {
20 | val arraySearch = intArrayOf(2, 5, 8, 12, 16, 23, 38, 56, 72, 91)
21 | val result = BinarySearchRecursive()
22 | .binarySearch(arraySearch, 0, arraySearch.size - 1, 100)
23 | println(result)
24 | }
--------------------------------------------------------------------------------
/src/algorithms/recursive/LongestPalindromic.kt:
--------------------------------------------------------------------------------
1 | package algorithms.recursive
2 |
3 | class LongestPalindromic {
4 | private var palindrome: String = ""
5 | fun longestPalindrome(s: String): String {
6 | return recursivePalindrome(s)
7 | }
8 |
9 | private fun recursivePalindrome(sentence: String): String {
10 | if (sentence.length <= palindrome.length) {
11 | return palindrome
12 | }
13 | if (sentence.reversed() == sentence && sentence.length > palindrome.length) {
14 | palindrome = sentence
15 | }
16 |
17 | recursivePalindrome(sentence.substring(0, sentence.length - 1))
18 | recursivePalindrome(sentence.substring(1, sentence.length))
19 | return palindrome
20 | }
21 | }
22 |
23 | fun main() {
24 | val longestPalindromic = LongestPalindromic()
25 | val result = longestPalindromic.longestPalindrome("abacdgfdcaba")
26 |
27 | println(result)
28 | }
--------------------------------------------------------------------------------
/src/algorithms/search/BinarySearch.kt:
--------------------------------------------------------------------------------
1 | package algorithms.search
2 |
3 | class BinarySearch {
4 | fun binarySearch(arr: IntArray, key: Int): Int {
5 | var left = 0
6 | var right = arr.size - 1
7 | var middle = right / 2
8 |
9 | while (left <= right) {
10 | when {
11 | arr[middle] == key -> {
12 | return middle
13 | }
14 | key > arr[middle] -> {
15 | left = middle + 1
16 | }
17 | key < arr[middle] -> {
18 | right = middle - 1
19 | }
20 | }
21 |
22 | middle = (left + right) / 2
23 | }
24 |
25 | return -1
26 | }
27 | }
28 |
29 | fun main() {
30 | val binarySearch = BinarySearch()
31 | val array = intArrayOf(2, 5, 8, 12, 16, 23, 38, 56, 72, 91)
32 | val result = binarySearch.binarySearch(array, 56)
33 | println(result)
34 | val result2 = binarySearch.binarySearch(array, 100)
35 | println(result2)
36 | }
--------------------------------------------------------------------------------
/src/algorithms/search/InterpolationSearch.kt:
--------------------------------------------------------------------------------
1 | package algorithms.search
2 |
3 | class InterpolationSearch {
4 |
5 | /**
6 | * Interpolation search is an algorithm which finds the position of a target value within an array (Sorted)
7 | *
8 | * Worst-case performance O(n)
9 | * Best-case performance O(1)
10 | * Average performance O(log log n)
11 | * Worst-case space complexity O(1)
12 | */
13 |
14 | /**
15 | * @param arr is an array where the element should be found
16 | * @param lo array starting index
17 | * @param hi array ending index
18 | * @param x is an element which should be found
19 | * @return index of the element
20 | */
21 |
22 | fun interpolationSearch(arr: IntArray, lo: Int,
23 | hi: Int, x: Int): Int {
24 | val pos: Int
25 |
26 | if (lo <= hi && x >= arr[lo] && x <= arr[hi]) {
27 |
28 | pos = (lo
29 | + ((hi - lo) / (arr[hi] - arr[lo])
30 | * (x - arr[lo])))
31 |
32 | if (arr[pos] == x) return pos
33 |
34 | if (arr[pos] < x) return interpolationSearch(arr, pos + 1, hi,
35 | x)
36 |
37 | if (arr[pos] > x) return interpolationSearch(arr, lo, pos - 1,
38 | x)
39 | }
40 | return -1
41 | }
42 | }
--------------------------------------------------------------------------------
/src/algorithms/search/LinearSearch.kt:
--------------------------------------------------------------------------------
1 | package algorithms.search
2 |
3 | class LinearSearch {
4 |
5 | fun linearSearch(arr: IntArray, key: Int): Int {
6 | for (i in arr.indices) {
7 | if (arr[i] == key) {
8 | return i
9 | }
10 | }
11 | return -1
12 | }
13 | }
--------------------------------------------------------------------------------
/src/algorithms/search/TernarySearch.kt:
--------------------------------------------------------------------------------
1 | package algorithms.search
2 |
3 | class TernarySearch {
4 | fun ternarySearch(l: Double, r: Double, func: (Double) -> Double, eps: Double = 1e-3): Double {
5 | var left = l
6 | var right = r
7 | while (right - left > eps) {
8 | val midFirst = left + (right - left) / 3
9 | val midSecond = right - (right - left) / 3
10 | if (func(midFirst) < func(midSecond)) {
11 | left = midFirst
12 | } else {
13 | right = midSecond
14 | }
15 | }
16 | return left
17 | }
18 | }
--------------------------------------------------------------------------------
/src/algorithms/sliding_window/MaximumOfValue.kt:
--------------------------------------------------------------------------------
1 | package algorithms.sliding_window
2 |
3 |
4 | class SlidingWindow {
5 | fun maximumOfValue(arr: IntArray, k: Int): Int {
6 | var maxSum = 0
7 | for (i in 0 until k) {
8 | maxSum += arr[i]
9 | }
10 | var windowSum = maxSum
11 | for (i in k until arr.size) {
12 | windowSum += arr[i] - arr[i - k]
13 | maxSum = maxOf(maxSum, windowSum)
14 | }
15 | return maxSum
16 | }
17 | }
18 |
19 |
20 |
21 |
22 | fun main() {
23 | println(
24 | SlidingWindow().maximumOfValue
25 | (
26 | intArrayOf(1, 4, 2, 10, 2, 3, 1, 0, 20),
27 | 4
28 | )
29 | )
30 | }
--------------------------------------------------------------------------------
/src/algorithms/sliding_window/lengthOfLongestSubstring.kt:
--------------------------------------------------------------------------------
1 | package algorithms.sliding_window
2 |
3 | fun lengthOfLongestSubstring(s: String): Int {
4 | var left = 0
5 | var right = 0
6 | var max = 0
7 | var hashSet = mutableSetOf()
8 | while (right < s.length) {
9 | if (hashSet.contains(s[right]).not()) {
10 | hashSet.add(s[right])
11 | right++
12 | max = maxOf(max, hashSet.size)
13 | } else {
14 | hashSet.remove(s[left])
15 | left++
16 | }
17 | }
18 | return max
19 | }
--------------------------------------------------------------------------------
/src/algorithms/sorting/BubbleSort.kt:
--------------------------------------------------------------------------------
1 | package algorithms.sorting
2 |
3 | fun bubbleSort(array: IntArray) {
4 | for (i in array.indices) {
5 | for (j in 0 until array.size - 1) {
6 | if (array[j] > array[j + 1]) {
7 | val temp = array[j]
8 | array[j] = array[j + 1]
9 | array[j + 1] = temp
10 | }
11 | }
12 | }
13 | }
14 |
15 | fun main() {
16 | val numbers = intArrayOf(99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0)
17 | bubbleSort(numbers)
18 | println(numbers.contentToString())
19 | }
--------------------------------------------------------------------------------
/src/algorithms/sorting/InsertionSort.kt:
--------------------------------------------------------------------------------
1 | package algorithms.sorting
2 |
3 | fun insertionSort(array: ArrayList){
4 |
5 | for (i in array.indices){
6 | if (array[i] <= array[0]){
7 | array.add(0,array.removeAt(i))
8 | } else {
9 | if (array[i] < array[i-1]){
10 | for (j in 1 until i){
11 | if (array[i] < array[j]){
12 | array.add(j, array.removeAt(i))
13 | break
14 | }
15 | }
16 | }
17 | }
18 | }
19 | }
20 |
21 |
22 |
23 |
24 | fun main(){
25 | val numbers = ArrayList(listOf(99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0))
26 | insertionSort(numbers)
27 | println(numbers)
28 |
29 | }
--------------------------------------------------------------------------------
/src/algorithms/sorting/MergeSort.kt:
--------------------------------------------------------------------------------
1 | package algorithms.sorting
2 |
3 | class MergeSort {
4 | fun mergeSort(array: List): List {
5 | if (array.size == 1) {
6 | return array
7 | }
8 | val left = array.subList(0, array.size / 2)
9 | val right = array.subList(array.size / 2, array.size)
10 | return merge(mergeSort(left), mergeSort(right))
11 | }
12 |
13 | private fun merge(left: List, right: List): List {
14 | val result = ArrayList()
15 | var leftIndex = 0
16 | var rightIndex = 0
17 | while (leftIndex < left.size && rightIndex < right.size) {
18 | if (left[leftIndex] < right[rightIndex]) {
19 | result.add(left[leftIndex])
20 | leftIndex++
21 | } else {
22 | result.add(right[rightIndex])
23 | rightIndex++
24 | }
25 | }
26 | val leftRemaining = left.subList(leftIndex, left.size)
27 | val rightRemaining = right.subList(rightIndex, right.size)
28 | result.addAll(leftRemaining)
29 | result.addAll(rightRemaining)
30 | return result
31 | }
32 | }
33 |
34 | fun main() {
35 | val mergeSort = MergeSort()
36 | val numbers = ArrayList(listOf(99, 1, 7, 2, 1, 5, 61, 67, 183, 4, 0))
37 | println(mergeSort.mergeSort(numbers))
38 | }
--------------------------------------------------------------------------------
/src/algorithms/sorting/QuickSort.kt:
--------------------------------------------------------------------------------
1 | package algorithms.sorting
2 |
3 |
4 | class QuickSort {
5 | fun quickSort(arr: IntArray, low: Int, high: Int) {
6 | if (low < high) {
7 | val pIndex = partition(arr, low, high)
8 | quickSort(arr, low, pIndex - 1)
9 | quickSort(arr, pIndex + 1, high)
10 | }
11 | }
12 |
13 | private fun partition(arr: IntArray, low: Int, high: Int): Int {
14 | val pivot = arr[high]
15 | var i = low - 1
16 | for (j in low until high) {
17 | if (arr[j] <= pivot) {
18 | i++
19 | val temp = arr[i]
20 | arr[i] = arr[j]
21 | arr[j] = temp
22 | }
23 | }
24 | val temp = arr[i + 1]
25 | arr[i + 1] = arr[high]
26 | arr[high] = temp
27 | return i + 1
28 | }
29 |
30 | }
31 |
32 | fun main() {
33 | val numbers = intArrayOf(99, 44, 6, 2, 1, 5, 63, 87, 283, 4, 0)
34 | val quickSort = QuickSort()
35 | quickSort.quickSort(numbers, 0, numbers.size - 1)
36 | println(numbers.contentToString())
37 | }
--------------------------------------------------------------------------------
/src/algorithms/sorting/SelectionSort.kt:
--------------------------------------------------------------------------------
1 | package algorithms.sorting
2 |
3 | fun selectionSort(array: IntArray): IntArray {
4 | for (i in array.indices) {
5 | var smallest = i
6 | for (j in i until array.size) {
7 | if (array[j] < array[smallest]) {
8 | smallest = j
9 | }
10 | }
11 | val temp = array[i]
12 | array[i] = array[smallest]
13 | array[smallest] = temp
14 | }
15 | return array
16 | }
17 |
18 | fun main() {
19 | val numbers = intArrayOf(99, 44, 6, 2, 1, 5, 63, 87, 283, 14, 0)
20 | println(selectionSort(numbers).contentToString())
21 | }
--------------------------------------------------------------------------------
/src/algorithms/twopointer/ThreeSum.kt:
--------------------------------------------------------------------------------
1 | //Given an integer array nums, return all the triplets [nums[i], nums[j], nums[
2 | //k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
3 | //
4 | // Notice that the solution set must not contain duplicate triplets.
5 | //
6 | //
7 | // Example 1:
8 | // Input: nums = [-1,0,1,2,-1,-4]
9 | //Output: [[-1,-1,2],[-1,0,1]]
10 | // Example 2:
11 | // Input: nums = []
12 | //Output: []
13 | // Example 3:
14 | // Input: nums = [0]
15 | //Output: []
16 | //
17 | //
18 | // Constraints:
19 | //
20 | //
21 | // 0 <= nums.length <= 3000
22 | // -10⁵ <= nums[i] <= 10⁵
23 | //
24 | // Related Topics Array Two Pointers Sorting 👍 13427 👎 1296
25 |
26 |
27 | package algorithms.twopointer
28 |
29 | class ThreeSum {
30 | fun solution() {
31 | }
32 |
33 | //below code will be used for submission to leetcode (using plugin of course)
34 | //leetcode submit region begin(Prohibit modification and deletion)
35 | class Solution {
36 | fun threeSum(nums: IntArray): List> {
37 | var res = HashSet>()
38 | nums.sort()
39 | for (i in 0 until nums.lastIndex - 1) {
40 | var j = i + 1
41 | var k = nums.lastIndex
42 | val tmp = -nums[i]
43 | while (j < k) {
44 | val sum = nums[j] + nums[k]
45 | when {
46 | sum == tmp -> {
47 | res.add(listOf(nums[i], nums[j], nums[k]))
48 | j++
49 | k--
50 | }
51 | sum < tmp -> {
52 | j++
53 | }
54 | else -> {
55 | k--
56 | }
57 | }
58 | }
59 | }
60 | return res.toList()
61 | }
62 | }
63 | //leetcode submit region end(Prohibit modification and deletion)
64 |
65 | }
66 |
67 | fun main() {}
68 |
69 |
70 |
--------------------------------------------------------------------------------
/src/codility/BinaryGap.kt:
--------------------------------------------------------------------------------
1 | package codility
2 |
3 | class BinaryGap {
4 | fun solution(n: Int): Int {
5 | val binary: String = n.toString(2)
6 | var longestBinaryGap = 0
7 | var stateOne = 0
8 | var countZero = 0
9 | for (i in binary.indices) {
10 | if (binary[i] == '1') {
11 | stateOne++
12 | }
13 | if (stateOne == 1 && binary[i] == '0') {
14 | countZero++
15 | } else if (stateOne == 2) {
16 | longestBinaryGap = maxOf(longestBinaryGap, countZero)
17 | countZero = 0
18 | stateOne = 1
19 | }
20 | }
21 | return longestBinaryGap
22 | }
23 | }
24 |
25 | fun main() {
26 | BinaryGap().solution(2147483647)
27 | }
28 |
--------------------------------------------------------------------------------
/src/codility/Bracket.kt:
--------------------------------------------------------------------------------
1 | package codility
2 |
3 | import java.util.*
4 |
5 | class Bracket {
6 | fun solution(S: String): Int {
7 | // write your code in Kotlin 1.3.11 (Linux)
8 | val pairs = mapOf('{' to '}', '[' to ']', '(' to ')')
9 | val stack = Stack()
10 | for (i in S.indices) {
11 | if (S[i] == '{' || S[i] == '(' || S[i] == '[') {
12 | stack.push(S[i])
13 | } else {
14 | if (stack.isEmpty()) return 0
15 | if (S[i] != pairs[stack.peek()]) return 0
16 | stack.pop()
17 | }
18 | }
19 | return if (stack.isEmpty()) 1 else 0
20 |
21 | }
22 | }
23 |
24 | fun main() {
25 | println(Bracket().solution("{[()()]}}}}}}()}"))
26 | }
27 |
--------------------------------------------------------------------------------
/src/codility/CyclicRotation.kt:
--------------------------------------------------------------------------------
1 | package codility
2 |
3 | class CyclicRotation {
4 | fun solution(A: IntArray, K: Int): IntArray {
5 | if (A.isEmpty()) return A
6 | var k = K
7 | k %= A.size
8 | reverse(A, 0, A.size - 1)
9 | reverse(A, 0, k - 1)
10 | reverse(A, k, A.size - 1)
11 | return A
12 | }
13 |
14 | fun reverse(arr: IntArray, l: Int, r: Int) {
15 | var left = l
16 | var right = r
17 | while (left < right) {
18 | val temp = arr[left]
19 | arr[left] = arr[right]
20 | arr[right] = temp
21 | left++
22 | right--
23 | }
24 | }
25 | }
--------------------------------------------------------------------------------
/src/codility/FibonacciCodility.kt:
--------------------------------------------------------------------------------
1 | package codility
2 |
3 | class FibonacciCodility {
4 |
5 | fun solution(n: Int): Int {
6 |
7 | if (n == 1) return 1 else if (n == 2) return 1 else if(n == 0) return 0
8 | var previousNumber1 = 1
9 | var previousNumber2 = 1
10 | var result = previousNumber2 + previousNumber1
11 | for (i in 3..n) {
12 | result = previousNumber2 + previousNumber1
13 | previousNumber2 = previousNumber1
14 | previousNumber1 = result
15 | }
16 | return result
17 | }
18 | }
--------------------------------------------------------------------------------
/src/codility/FirstMissingPositive.kt:
--------------------------------------------------------------------------------
1 | package codility
2 |
3 | class FirstMissingPositive {
4 | fun firstMissingPositive(nums: IntArray): Int {
5 | var count = 0
6 | for (n in nums) {
7 | if (n > 0) ++count
8 | }
9 | run {
10 | var i = 0
11 | while (i < nums.size) {
12 | if (nums[i] != i + 1 && nums[i] > 0 && nums[i] <= count && nums[nums[i] - 1] != nums[i]
13 | ) {
14 | swap(nums, i, nums[i] - 1)
15 | --i
16 | }
17 | ++i
18 | }
19 | }
20 | for (i in 1..count) {
21 | if (nums[i - 1] != i) {
22 | return i
23 | }
24 | }
25 | return 1 + count
26 | }
27 |
28 | fun swap(a: IntArray, i: Int, j: Int) {
29 | val t = a[i]
30 | a[i] = a[j]
31 | a[j] = t
32 | }
33 | }
--------------------------------------------------------------------------------
/src/codility/FirstUniqueNumber.kt:
--------------------------------------------------------------------------------
1 | package codility
2 |
3 | class FirstUniqueNumber {
4 | fun solution(A: IntArray): Int {
5 | // write your code in Kotlin 1.3.11 (Linux)
6 | val hashMap = HashMap()
7 | for (i in A.indices) {
8 | hashMap[A[i]] = hashMap.getOrDefault(A[i], 0) + 1
9 | }
10 | for (i in A.indices) {
11 | if (hashMap[A[i]] == 1) return A[i]
12 | }
13 |
14 | return -1
15 | }
16 |
17 | }
18 |
19 | fun main() {
20 | println(FirstUniqueNumber().solution(intArrayOf(4, 10, 5, 4, 2, 10)))
21 | }
--------------------------------------------------------------------------------
/src/codility/Fish.kt:
--------------------------------------------------------------------------------
1 | package codility
2 |
3 | import java.util.*
4 |
5 |
6 | class Fish {
7 | fun solution(A: IntArray, B: IntArray): Int {
8 | val livingIndices = Stack()
9 | for (i in A.indices) {
10 | if (B[i] == 0) {
11 | while (!livingIndices.empty() && B[livingIndices.peek()] == 1 &&
12 | A[i] > A[livingIndices.peek()]) {
13 | livingIndices.pop()
14 | }
15 | if (!(!livingIndices.empty() && B[livingIndices.peek()] == 1)) {
16 | livingIndices.push(i)
17 | }
18 | } else {
19 | livingIndices.push(i)
20 | }
21 | }
22 | return livingIndices.size
23 | }
24 |
25 | }
26 |
27 | fun main() {
28 | println(Fish().solution(intArrayOf(4, 3, 2, 1, 5), intArrayOf(0, 1, 0, 0, 0)))
29 | }
--------------------------------------------------------------------------------
/src/codility/FrogRiverOne.kt:
--------------------------------------------------------------------------------
1 | package codility
2 |
3 | class FrogRiverOne {
4 | fun solution(X: Int, A: IntArray): Int {
5 | val list = IntArray(X) { -1 }
6 | var maxCounters = -1
7 | var minCounters = 0
8 | for (i in A.indices) {
9 | if (A[i] <= X && list[A[i] - 1] == -1) {
10 | list[A[i] - 1] = i
11 | maxCounters = maxOf(maxCounters, i)
12 | minCounters++
13 | }
14 | }
15 | return if (minCounters == X) return maxCounters else -1
16 | }
17 | }
18 |
19 | fun main() {
20 | println(FrogRiverOne().solution(5, intArrayOf(1, 2, 3, 9, 10, 4,5)))
21 | }
22 |
--------------------------------------------------------------------------------
/src/codility/MaxCounters.kt:
--------------------------------------------------------------------------------
1 | package codility
2 |
3 | class MaxCounters {
4 | fun solution(N: Int, A: IntArray): IntArray {
5 | val result = IntArray(N) { 0 }
6 | var maxCounters = 0
7 | var lasIncrease = 0
8 | for (i in A.indices) {
9 | if (A[i] == N + 1) {
10 | lasIncrease = maxCounters
11 | } else {
12 | result[A[i] - 1] = maxOf(lasIncrease, result[A[i] - 1])
13 | result[A[i] - 1]++
14 | maxCounters = maxOf(maxCounters, result[A[i] - 1])
15 | }
16 | }
17 |
18 | for (i in result.indices) {
19 | result[i] = maxOf(result[i], lasIncrease)
20 | }
21 | return result
22 | }
23 | }
24 |
25 | fun main() {
26 | MaxCounters().solution(5, intArrayOf(3, 4, 4, 6, 1, 4, 4))
27 | }
--------------------------------------------------------------------------------
/src/codility/NailingFlanks.kt:
--------------------------------------------------------------------------------
1 | package codility
2 |
3 | import java.util.*
4 |
5 |
6 | class NailingFlanks {
7 |
8 | fun solution(A: IntArray, B: IntArray, C: IntArray): Int {
9 | // the main algorithm is that getting the minimal index of nails which
10 | // is needed to nail every plank by using the binary search
11 | val N = A.size
12 | val M = C.size
13 | // two dimension array to save the original index of array C
14 | val sortedNail = Array(M) { IntArray(2) }
15 | for (i in 0 until M) {
16 | sortedNail[i][0] = C[i]
17 | sortedNail[i][1] = i
18 | }
19 | // use the lambda expression to sort two dimension array
20 | Arrays.sort(sortedNail) { x: IntArray, y: IntArray -> x[0] - y[0] }
21 | var result = 0
22 | for (i in 0 until N) { //find the earlist position that can nail each plank, and the max value for all planks is the result
23 | result = getMinIndex(A[i], B[i], sortedNail, result)
24 | if (result == -1) return -1
25 | }
26 | return result + 1
27 | }
28 |
29 | // for each plank , we can use binary search to get the minimal index of the
30 | // sorted array of nails, and we should check the candidate nails to get the
31 | // minimal index of the original array of nails.
32 | private fun getMinIndex(startPlank: Int, endPlank: Int, nail: Array, preIndex: Int): Int {
33 | var min = 0
34 | var max = nail.size - 1
35 | var minIndex = -1
36 | while (min <= max) {
37 | val mid = (min + max) / 2
38 | if (nail[mid][0] < startPlank) min = mid + 1 else if (nail[mid][0] > endPlank) max = mid - 1 else {
39 | max = mid - 1
40 | minIndex = mid
41 | }
42 | }
43 | if (minIndex == -1) return -1
44 | var minIndexOrigin = nail[minIndex][1]
45 | //find the smallest original position of nail that can nail the plank
46 | for (i in minIndex until nail.size) {
47 | if (nail[i][0] > endPlank) break
48 | minIndexOrigin = Math.min(minIndexOrigin, nail[i][1])
49 | // we need the maximal index of nails to nail every plank, so the
50 | // smaller index can be omitted
51 | if (minIndexOrigin <= preIndex) return preIndex
52 | }
53 | return minIndexOrigin
54 | }
55 | }
56 |
57 | fun main() {
58 | println(NailingFlanks().solution(intArrayOf(1, 4, 5, 8), intArrayOf(4, 5, 9, 10), intArrayOf(4, 6, 7, 10, 2)))
59 | }
--------------------------------------------------------------------------------
/src/codility/NumberOfDiscIntersections.kt:
--------------------------------------------------------------------------------
1 | package codility
2 |
3 | /*
4 | We draw N discs on a plane. The discs are numbered from 0 to N − 1. An array A of N non-negative integers, specifying the radiuses of the discs, is given. The J-th disc is drawn with its center at (J, 0) and radius A[J].
5 |
6 | We say that the J-th disc and K-th disc intersect if J ≠ K and the J-th and K-th discs have at least one common point (assuming that the discs contain their borders).
7 |
8 | The figure below shows discs drawn for N = 6 and A as follows:
9 |
10 | A[0] = 1
11 | A[1] = 5
12 | A[2] = 2
13 | A[3] = 1
14 | A[4] = 4
15 | A[5] = 0
16 |
17 |
18 | There are eleven (unordered) pairs of discs that intersect, namely:
19 |
20 | discs 1 and 4 intersect, and both intersect with all the other discs;
21 | disc 2 also intersects with discs 0 and 3.
22 | Write a function:
23 |
24 | class Solution { public int solution(int[] A); }
25 |
26 | that, given an array A describing N discs as explained above, returns the number of (unordered) pairs of intersecting discs. The function should return −1 if the number of intersecting pairs exceeds 10,000,000.
27 |
28 | Given array A shown above, the function should return 11, as explained above.
29 |
30 | Write an efficient algorithm for the following assumptions:
31 |
32 | N is an integer within the range [0..100,000];
33 | each element of array A is an integer within the range [0..2,147,483,647].
34 |
35 |
36 | */
37 |
38 |
39 |
40 |
41 |
42 | import kotlin.math.abs
43 |
44 | class NumberOfDiscIntersections {
45 | fun solution(A: IntArray): Int {
46 | val n = A.size
47 | val starts = IntArray(n + 1)
48 | val ends = IntArray(n + 1)
49 | for (i in 0 until n) {
50 | val discRadius = abs(A[i])
51 | val indexOfBeginning = i.toLong() - discRadius.toLong()
52 | starts[(if (indexOfBeginning < 0) 0 else indexOfBeginning).toInt()]++
53 | val indexOfEnd: Long = i.toLong() + discRadius.toLong()
54 | val result = if (indexOfEnd > n) n else indexOfEnd
55 | ends[result.toString().toInt()]++
56 | }
57 | var numberOfIntersections = 0
58 | var numberOfActiveCircles = 0
59 | for (i in 0 until n + 1) {
60 | val numberOfNewCircles = starts[i]
61 | if (numberOfNewCircles > 0) {
62 | numberOfIntersections += (numberOfActiveCircles * numberOfNewCircles
63 | + (numberOfNewCircles - 1) * numberOfNewCircles / 2)
64 | numberOfActiveCircles += numberOfNewCircles
65 | if (numberOfIntersections > 10000000) {
66 | return -1
67 | }
68 | }
69 | if (ends[i] > 0) {
70 | numberOfActiveCircles -= ends[i]
71 | }
72 | }
73 | return numberOfIntersections
74 | }
75 | }
--------------------------------------------------------------------------------
/src/codility/NumberSolitaire.kt:
--------------------------------------------------------------------------------
1 | package codility
2 |
3 | class NumberSolitaire {
4 | fun solution(A: IntArray): Int {
5 | val lens = A.size
6 | val dp = IntArray(6)
7 | for (i in 0..5) {
8 | dp[i] = A[0]
9 | }
10 | for (i in 1 until lens) {
11 | dp[i % 6] = getMax6(dp) + A[i]
12 | println(dp.contentToString())
13 | }
14 | return dp[(lens - 1) % 6]
15 | }
16 |
17 | private fun getMax6(dp: IntArray): Int {
18 | var max = dp[0]
19 | for (i in 1 until dp.size) {
20 | max = maxOf(max, dp[i])
21 | }
22 | return max
23 | }
24 | }
25 |
26 | fun main() {
27 | println(NumberSolitaire().solution(intArrayOf(1, 2, 3, 4, 5, 6, 7, -8, -9)))
28 | }
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
--------------------------------------------------------------------------------
/src/codility/OddOccurrencesInArray.kt:
--------------------------------------------------------------------------------
1 | package codility
2 |
3 | class OddOccurrencesInArray {
4 | fun solution(A: IntArray): Int {
5 | var result = 0
6 | A.forEach {
7 | result = result.xor(it)
8 | }
9 | return result
10 | }
11 | }
12 |
13 | fun main() {
14 | OddOccurrencesInArray().solution(intArrayOf(1, 3, 4, 5, 6))
15 | }
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
24 |
25 |
26 |
27 |
--------------------------------------------------------------------------------
/src/codility/StoneWall.kt:
--------------------------------------------------------------------------------
1 | package codility
2 |
3 | import java.util.*
4 |
5 |
6 | class StoneWall {
7 | fun solution(H: IntArray): Int {
8 |
9 | // main idea: need to use "stack" to check when we need a new block
10 | val st = Stack()
11 | var numBlock = 0
12 |
13 | // note: H[i] is the ith height of the wall
14 | for (i in H.indices) {
15 |
16 | // step 1: "stack is not empty" AND "from high to low"
17 | // then, "pop" (it is the key point, be careful)
18 | while (st.isEmpty() == false && st.peek() > H[i]) {
19 | st.pop()
20 | }
21 | // step 2: if the stack is empty
22 | if (st.isEmpty()) {
23 | numBlock++ // add a block
24 | st.push(H[i]) // push the height
25 | } else if (st.peek() == H[i]) {
26 | } else if (st.peek() < H[i]) {
27 | numBlock++ // add a block
28 | st.push(H[i]) // push the height
29 | }
30 | }
31 | return numBlock
32 | }
33 | }
--------------------------------------------------------------------------------
/src/data_structure/graph/Graph.kt:
--------------------------------------------------------------------------------
1 | package data_structure.graph
2 |
3 | import java.util.*
4 | import kotlin.collections.ArrayList
5 |
6 | class Graph(var numberOfNodes: Int = 0, var adjacentList: Hashtable> = Hashtable()) {
7 | fun addVertex(node: Int) {
8 | adjacentList[node] = ArrayList()
9 | numberOfNodes++
10 | }
11 |
12 | fun addEdge(node1: Int, node2: Int) {
13 | adjacentList[node1]?.add(node2)
14 | adjacentList[node2]?.add(node1)
15 | }
16 |
17 | fun showConnections() {
18 | val keys: Array = adjacentList.keys.toTypedArray()
19 | for (key in keys) {
20 | println(key.toString() + " --> " + adjacentList[key.toString().toInt()])
21 | }
22 | }
23 | }
24 |
25 | fun main() {
26 | val graph = Graph()
27 | graph.addVertex(5)
28 | graph.addVertex(54)
29 | graph.addVertex(44)
30 | graph.addEdge(5, 54)
31 | graph.addEdge(5, 44)
32 | graph.showConnections()
33 | }
--------------------------------------------------------------------------------
/src/data_structure/queue/QueueUsingStack.kt:
--------------------------------------------------------------------------------
1 | package data_structure.queue
2 |
3 | import java.util.*
4 |
5 |
6 | class QueueUsingStack {
7 | var queueStack = Stack()
8 |
9 | private var revStack = Stack()
10 |
11 | fun push(x: Int) {
12 | if (queueStack.size == 0) {
13 | queueStack.push(x)
14 | } else {
15 | while (queueStack.size != 0) {
16 | revStack.push(queueStack.pop())
17 | }
18 | revStack.push(x)
19 |
20 | while (revStack.size != 0) {
21 | queueStack.push(revStack.pop())
22 | }
23 | }
24 | }
25 |
26 | fun pop(): Int? {
27 | return if (queueStack.size > 0) {
28 | queueStack.pop()
29 | } else {
30 | null
31 | }
32 | }
33 |
34 |
35 | fun peek(): Int? {
36 | return if (queueStack.size > 0) {
37 | queueStack[queueStack.size - 1]
38 | } else {
39 | null
40 | }
41 | }
42 |
43 | fun empty() = queueStack.size == 0
44 |
45 | }
46 |
47 |
48 | fun main() {
49 | val myQueue = QueueUsingStack()
50 | myQueue.push(10)
51 | myQueue.push(20)
52 | myQueue.push(30)
53 | println("queue: " + myQueue.queueStack)
54 | println("peek: " + myQueue.peek())
55 | println("pop: " + myQueue.pop())
56 | println("queue: " + myQueue.queueStack)
57 | println("peek: " + myQueue.peek())
58 | println("is queue empty: " + myQueue.empty())
59 | }
--------------------------------------------------------------------------------
/src/data_structure/queue/QueuesUsingLinkedList.kt:
--------------------------------------------------------------------------------
1 | package data_structure.queue
2 |
3 |
4 | class QueuesUsingLinkedList {
5 | inner class Node(var value: String?) {
6 | var next: Node? = null
7 | }
8 |
9 | var first: Node? = null
10 | var last: Node? = null
11 | var length = 0
12 |
13 |
14 | fun enqueue(value: String?) {
15 | val newNode: Node? = Node(value)
16 | if (length == 0) {
17 | first = newNode
18 | } else {
19 | last?.next = newNode
20 | }
21 | last = newNode
22 | length++
23 | }
24 |
25 | fun dequeue() {
26 | if (length > 0) {
27 | first = first?.next
28 | if (length == 1) {
29 | last = null
30 | }
31 | length--
32 | }
33 | }
34 |
35 | fun isEmpty() = length == 0
36 |
37 | fun peek(): String? {
38 | return if (length > 0) {
39 | first?.value
40 | } else {
41 | null
42 | }
43 | }
44 |
45 | }
46 |
47 |
48 | fun main() {
49 | val myQueue = QueuesUsingLinkedList()
50 | println("is Empty : " + myQueue.isEmpty())
51 | println("peek : " + myQueue.peek())
52 | myQueue.enqueue("Apple")
53 | myQueue.enqueue("Ball")
54 | myQueue.enqueue("Cat")
55 | println("peek :" + myQueue.peek())
56 | myQueue.dequeue()
57 | println("peek :" + myQueue.peek())
58 |
59 | }
--------------------------------------------------------------------------------
/src/data_structure/stack/MinStack.kt:
--------------------------------------------------------------------------------
1 | package data_structure.stack
2 |
3 | import java.util.*
4 |
5 | class MinStack() {
6 | private val stack = Stack()
7 | private val minStack = Stack()
8 |
9 | fun push(x: Int) {
10 | stack.push(x)
11 |
12 | if (minStack.empty() || x <= minStack.peek()) {
13 | minStack.push(x)
14 | }
15 | }
16 |
17 | fun pop() {
18 | val el = stack.pop()
19 |
20 | if (!minStack.empty() && el == minStack.peek()) {
21 | minStack.pop()
22 | }
23 | }
24 |
25 | fun top(): Int {
26 | return stack.peek()
27 | }
28 |
29 | fun getMin(): Int {
30 | return minStack.peek()
31 | }
32 | }
--------------------------------------------------------------------------------
/src/data_structure/stack/StackUsingLinkedList.kt:
--------------------------------------------------------------------------------
1 | package data_structure.stack
2 |
3 | class StackUsingLinkedList() {
4 | inner class Node(var value: Int) {
5 | var next: Node? = null
6 | }
7 |
8 | var first: Node? = null
9 | var last: Node? = null
10 | var length = -1
11 |
12 | fun push(value: Int) {
13 | val newNode: Node? = Node(value)
14 | if (length == -1) {
15 | last = newNode
16 | first = newNode
17 | } else {
18 | last?.next = newNode
19 | last = newNode
20 | }
21 | length++
22 | }
23 |
24 | fun pop(): Int {
25 |
26 | var current = first
27 | if (length == -1) {
28 | println("stack is empty")
29 | return -1
30 | } else {
31 | var i = 0
32 | while (i != length - 1) {
33 | current = current?.next
34 | i++
35 | }
36 |
37 | last = current
38 | last?.next = current?.next?.next
39 | }
40 | length--
41 |
42 | return current?.value as Int
43 | }
44 |
45 | fun peek(): Int {
46 | if (length == -1) {
47 | println("stack is empty")
48 | return -1
49 | }
50 | return last?.value as Int
51 | }
52 |
53 | fun size(): Int {
54 | return length
55 | }
56 |
57 | fun getStack() {
58 | var current = first
59 | while (current != null) {
60 | print("${current?.value} , ")
61 | current = current?.next
62 | }
63 | }
64 | }
65 |
66 |
67 | fun main() {
68 | val myStack = StackUsingLinkedList()
69 | myStack.push(15)
70 | myStack.push(16)
71 | var peek = myStack.peek()
72 | println("pek : $peek")
73 | myStack.push(17)
74 | myStack.push(18)
75 |
76 | println("size ${myStack.size()}")
77 | myStack.getStack()
78 | println()
79 | myStack.pop()
80 |
81 | println("size ${myStack.size()}")
82 | myStack.getStack()
83 | println()
84 | println("wait pop 10 data")
85 |
86 | for (i in 1..10) {
87 | myStack.push(18 + i)
88 | }
89 | println()
90 | myStack.getStack()
91 | println()
92 | myStack.pop()
93 | myStack.getStack()
94 | println()
95 | peek = myStack.peek()
96 | println("pek : $peek")
97 |
98 | }
99 |
100 |
101 |
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
--------------------------------------------------------------------------------
/src/data_structure/string/ReverseString.kt:
--------------------------------------------------------------------------------
1 | package data_structure.string
2 |
3 | import java.util.*
4 |
5 | class ReverseString {
6 | fun solution(s: String): String {
7 | var i = 0
8 | var j = s.length - 1
9 | val stringResult = s.toCharArray()
10 | while (i < j) {
11 | val temp = stringResult[j]
12 | stringResult[j] = stringResult[i]
13 | stringResult[i] = temp
14 | i++
15 | j--
16 | }
17 | return String(stringResult)
18 | }
19 |
20 |
21 | fun solutionPerWord(s: String): String {
22 | val stack = Stack()
23 | val stringBuilder = StringBuilder()
24 | repeat(s.length) {
25 | if (!s[it].isLetter() || it == s.lastIndex) {
26 |
27 | if (it == s.lastIndex && s[it].isLetter()) {
28 | stack.push(s[it])
29 | }
30 | while (stack.isNotEmpty()) {
31 | stringBuilder.append(stack.pop())
32 | }
33 | if (!s[it].isLetter()) {
34 | stringBuilder.append(s[it])
35 | }
36 |
37 | } else {
38 | stack.push(s[it])
39 | }
40 | }
41 | return stringBuilder.toString()
42 | }
43 | }
44 |
45 |
46 | fun main() {
47 | val reverseString = ReverseString()
48 | println(reverseString.solutionPerWord("Hello Github fani abdullah!"))
49 | }
--------------------------------------------------------------------------------
/src/data_structure/string/numberOfMatching.kt:
--------------------------------------------------------------------------------
1 | package data_structure.string
2 |
3 | class NumberOfMatching {
4 | fun numMatchingSubseq(S: String, words: Array): Int {
5 | return words.count { it.isSubsequenceOf(S) }
6 | }
7 |
8 | private fun String.isSubsequenceOf(S: String): Boolean {
9 | var p = 0
10 | var q = 0
11 | while (p < S.length && q < this.length) {
12 | if (S[p] == this[q]) {
13 | p++
14 | q++
15 | } else {
16 | p++
17 | }
18 | }
19 | return q == this.length
20 | }
21 |
22 | }
--------------------------------------------------------------------------------
/src/data_structure/tree/BinaryTree.kt:
--------------------------------------------------------------------------------
1 | package data_structure.tree
2 |
3 |
4 | class TreeNodeString(var treeValue: String?) {
5 | var right: TreeNodeString? = null
6 | var left: TreeNodeString? = null
7 | }
8 |
9 | class TreeHelper() {
10 |
11 | fun preOrderPrint(node: TreeNodeString?): String {
12 | if (node == null) {
13 | return ""
14 | }
15 | var result = node.treeValue
16 | val resultLeft = preOrderPrint(node.left)
17 | result = result + resultLeft + preOrderPrint(node.right)
18 | return result
19 | }
20 |
21 | fun inOrderPrint(node: TreeNodeString?): String {
22 | if (node == null) {
23 | return ""
24 | }
25 | val resultLeft = inOrderPrint(node.left)
26 | var result = node.treeValue
27 | result = resultLeft + result + inOrderPrint(node.right)
28 | return result
29 | }
30 |
31 | fun postOrderPrint(node: TreeNodeString?): String {
32 | if (node == null) {
33 | return ""
34 | }
35 | val resultLeft = postOrderPrint(node.left)
36 | return resultLeft + postOrderPrint(node.right) + node.treeValue
37 | }
38 | }
39 |
40 |
41 | fun main() {
42 | val treeHelper = TreeHelper()
43 | val treeNode = TreeNodeString("A")
44 | treeNode.left = TreeNodeString("B")
45 | treeNode.left?.left = TreeNodeString("D")
46 | treeNode.left?.right = TreeNodeString("E")
47 | treeNode.left?.right?.left = TreeNodeString("H")
48 | treeNode.right = TreeNodeString("C")
49 | treeNode.right?.right = TreeNodeString("G")
50 | treeNode.right?.left = TreeNodeString("F")
51 |
52 | println(treeHelper.preOrderPrint(treeNode))
53 |
54 | println(treeHelper.inOrderPrint(treeNode))
55 |
56 | println(treeHelper.postOrderPrint(treeNode))
57 | }
58 |
--------------------------------------------------------------------------------
/src/data_structure/tree/GraphBFS.kt:
--------------------------------------------------------------------------------
1 | package data_structure.tree
2 |
3 | import java.util.*
4 |
5 |
6 | internal class Graph( // No. of vertices
7 | private val V: Int
8 | ) {
9 | private var adj: Array> = Array(V) { LinkedList() } //Adjacency Lists
10 |
11 | // Function to add an edge into the graph
12 | fun addEdge(v: Int, w: Int) {
13 | adj[v].add(w)
14 | }
15 |
16 | // prints BFS traversal from a given source s
17 | fun bfs(s: Int) {
18 | // Mark all the vertices as not visited(By default
19 | // set as false)
20 | var s = s
21 | val visited = BooleanArray(V)
22 |
23 | // Create a queue for BFS
24 | val queue = LinkedList()
25 |
26 | // Mark the current node as visited and enqueue it
27 | visited[s] = true
28 | queue.add(s)
29 | while (queue.size != 0) {
30 | // Dequeue a vertex from queue and print it
31 | s = queue.poll()
32 | print("$s ")
33 |
34 | // Get all adjacent vertices of the dequeued vertex s
35 | // If a adjacent has not been visited, then mark it
36 | // visited and enqueue it
37 | val i: Iterator = adj[s].listIterator()
38 | while (i.hasNext()) {
39 | val n = i.next()
40 | if (!visited[n]) {
41 | visited[n] = true
42 | queue.add(n)
43 | }
44 | }
45 | }
46 | }
47 |
48 | companion object {
49 | // Driver method to
50 | @JvmStatic
51 | fun main(args: Array) {
52 | val g = Graph(4)
53 | g.addEdge(0, 1)
54 | g.addEdge(0, 2)
55 | g.addEdge(1, 2)
56 | g.addEdge(2, 0)
57 | g.addEdge(2, 3)
58 | g.addEdge(3, 3)
59 | println(
60 | "Following is Breadth First Traversal " +
61 | "(starting from vertex 2)"
62 | )
63 | g.bfs(2)
64 | }
65 | }
66 |
67 | init {
68 | for (i in 0 until V) adj[i] = LinkedList()
69 | }
70 | }
71 |
72 |
73 | fun main() {
74 | val g = Graph(4)
75 |
76 | g.addEdge(0, 1)
77 | g.addEdge(0, 2)
78 | g.addEdge(1, 2)
79 | g.addEdge(2, 0)
80 | g.addEdge(2, 3)
81 | g.addEdge(3, 3)
82 |
83 | println(
84 | "Following is Breadth First Traversal " +
85 | "(starting from vertex 2)"
86 | )
87 |
88 | g.bfs(2)
89 | }
90 |
--------------------------------------------------------------------------------
/src/data_structure/tree/InsertionTree.kt:
--------------------------------------------------------------------------------
1 | package data_structure.tree
2 |
3 | import java.util.*
4 |
5 | class TreeNodeInt(key: Int?) {
6 | var treeValue: Int? = key
7 | var right: TreeNodeInt? = null
8 | var left: TreeNodeInt? = null
9 | }
10 |
11 | class TreeHelperInt() {
12 | var root: TreeNodeInt? = null
13 | var temp: TreeNodeInt? = null
14 |
15 | fun inOrderPrint(node: TreeNodeInt?) {
16 | if (node == null) {
17 | return
18 | }
19 | inOrderPrint(node.left)
20 | print("${node.treeValue} ")
21 | inOrderPrint(node.right)
22 | }
23 |
24 | fun insertTree(tempp: TreeNodeInt?, key: Int) {
25 | if (tempp == null) {
26 | root = TreeNodeInt(key)
27 | return
28 | }
29 | val q: Queue = LinkedList()
30 | q.add(tempp)
31 | while (!q.isEmpty()) {
32 | temp = q.peek()
33 | q.remove()
34 | if (temp?.left == null) {
35 | temp?.left = TreeNodeInt(key)
36 | break
37 | } else q.add(temp?.left)
38 | if (temp?.right == null) {
39 | temp?.right = TreeNodeInt(key)
40 | break
41 | } else q.add(temp?.right)
42 | }
43 | }
44 |
45 | fun deleteTree(tempDelete: TreeNodeInt?, key: Int) {
46 | if (tempDelete == null) {
47 | root = TreeNodeInt(key)
48 | return
49 | }
50 | val q: Queue = LinkedList()
51 | q.add(tempDelete)
52 | while (!q.isEmpty()) {
53 | temp = q.peek()
54 | q.remove()
55 | if (temp?.treeValue == key) {
56 | temp?.treeValue = -1
57 | temp?.left = null
58 | temp?.right = null
59 | break
60 | } else {
61 | q.add(temp?.left)
62 | q.add(temp?.right)
63 | }
64 |
65 | }
66 |
67 | }
68 |
69 | }
70 |
71 | fun main() {
72 | val myClass = TreeHelperInt()
73 | val root: TreeNodeInt?
74 | root = TreeNodeInt(10);
75 | root.left = TreeNodeInt(11);
76 | root.left?.left = TreeNodeInt(7);
77 | root.right = TreeNodeInt(9);
78 | root.right?.left = TreeNodeInt(15);
79 | root.right?.right = TreeNodeInt(18);
80 | myClass.root = root
81 |
82 | println("before")
83 | myClass.inOrderPrint(root)
84 | println()
85 | println("after insert")
86 | myClass.insertTree(root, 12)
87 | myClass.inOrderPrint(root)
88 |
89 | println("after Delete")
90 | myClass.deleteTree(root, 10)
91 | myClass.inOrderPrint(root)
92 |
93 | }
--------------------------------------------------------------------------------
/src/data_structure/tree/TreeBFS.kt:
--------------------------------------------------------------------------------
1 | package data_structure.tree
2 |
3 | import java.util.*
4 |
5 |
6 | class TreeBFS {
7 | // https://www.geeksforgeeks.org/level-node-tree-source-node-using-bfs/
8 |
9 |
10 | // function to determine level of each node starting
11 | // from x using BFS
12 | fun printLevels(graph: Vector>, V: Int, x: Int) {
13 | // array to store level of each node
14 | var x = x
15 | val level = IntArray(V)
16 | val marked = BooleanArray(V)
17 |
18 | // create a queue
19 | val que: Queue = LinkedList()
20 |
21 | // enqueue element x
22 | que.add(x)
23 |
24 | // initialize level of source node to 0
25 | level[x] = 0
26 |
27 | // marked it as visited
28 | marked[x] = true
29 |
30 | // do until queue is empty
31 | while (que.size > 0) {
32 |
33 | // get the first element of queue
34 | x = que.peek()
35 |
36 | // dequeue element
37 | que.remove()
38 |
39 | // traverse neighbors of node x
40 | for (i in graph[x].indices) {
41 | // b is neighbor of node x
42 | val b = graph[x][i]
43 |
44 | // if b is not marked already
45 | if (!marked[b]) {
46 |
47 | // enqueue b in queue
48 | que.add(b)
49 |
50 | // level of b is level of x + 1
51 | level[b] = level[x] + 1
52 |
53 | // mark b
54 | marked[b] = true
55 | }
56 | }
57 | }
58 |
59 | // display all nodes and their levels
60 | println(
61 | "Nodes"
62 | + " "
63 | + "Level"
64 | )
65 | for (i in 0 until V) println(" " + i + " --> " + level[i])
66 | }
67 | }
68 |
69 | fun main(){
70 | // adjacency graph for tree
71 | // adjacency graph for tree
72 | val V = 8
73 | val graph = Vector>()
74 |
75 | for (i in 0 until V + 1) graph.add(Vector())
76 |
77 | graph[0].add(1)
78 | graph[0].add(2)
79 | graph[1].add(3)
80 | graph[1].add(4)
81 | graph[1].add(5)
82 | graph[2].add(5)
83 | graph[2].add(6)
84 | graph[6].add(7)
85 |
86 | // call levels function with source as 0
87 |
88 | // call levels function with source as 0
89 | TreeBFS().printLevels(graph, V, 0)
90 | }
91 |
--------------------------------------------------------------------------------
/src/data_structure/tree/TreeTraversal.kt:
--------------------------------------------------------------------------------
1 | package data_structure.tree
2 |
3 | import java.util.*
4 |
5 | class TreeNode(var value: Int) {
6 | var left: TreeNode? = null
7 | var right: TreeNode? = null
8 | }
9 |
10 | class TreeTraversal {
11 | fun printLevelOrder(tree: TreeNode?) {
12 | val queue: Queue = LinkedList()
13 | queue.add(tree)
14 | while (!queue.isEmpty()) {
15 |
16 | val tempNode = queue.poll()
17 | print(tempNode?.value.toString() + " ")
18 |
19 | if (tempNode!!.left != null) {
20 | queue.add(tempNode.left)
21 | }
22 |
23 | if (tempNode.right != null) {
24 | queue.add(tempNode.right)
25 | }
26 | }
27 | }
28 |
29 | fun inOrder(tree: TreeNode?) {
30 | if (tree == null) {
31 | return
32 | }
33 | inOrder(tree.left)
34 | print("" + tree.value + " ")
35 | inOrder(tree.right)
36 | }
37 |
38 | fun inOrderStack(tree: TreeNode?) {
39 | val stack = Stack()
40 | var current = tree
41 | while (current != null) {
42 | current = current.left
43 | stack.add(current?.value)
44 | }
45 | }
46 |
47 | fun preOrder(tree: TreeNode?) {
48 | if (tree == null) {
49 | return
50 | }
51 | print("" + tree.value + " ")
52 | preOrder(tree.left)
53 | preOrder(tree.right)
54 | }
55 |
56 | fun postOrder(tree: TreeNode?) {
57 | if (tree == null) {
58 | return
59 | }
60 | postOrder(tree.left)
61 | postOrder(tree.right)
62 |
63 | print("" + tree.value + " ")
64 | }
65 |
66 | }
67 |
68 | fun main() {
69 | val tree = TreeNode(1)
70 | tree.left = TreeNode(2)
71 | tree.right = TreeNode(3)
72 | tree.left?.left = TreeNode(4)
73 | tree.left?.right = TreeNode(5)
74 | print("in order = ")
75 | TreeTraversal().inOrder(tree)
76 | println()
77 | print("pre order = ")
78 | TreeTraversal().preOrder(tree)
79 | println()
80 |
81 | print("post order = ")
82 | TreeTraversal().postOrder(tree)
83 | }
--------------------------------------------------------------------------------
/src/data_structure/trie/Trie.kt:
--------------------------------------------------------------------------------
1 | package data_structure.trie
2 |
3 | class Trie() {
4 |
5 | class TrieNode {
6 | val children = Array(26) { null }
7 | var isWord = false
8 | }
9 |
10 | val trieTree = TrieNode()
11 |
12 | /** Inserts a word into the trie. */
13 | fun insert(word: String) {
14 | var p = trieTree
15 |
16 | for (w in word) {
17 | val i = w - 'a'
18 | if (p.children[i] == null) p.children[i] = TrieNode()
19 | p = p.children[i]!!
20 | }
21 | p.isWord = true
22 | }
23 |
24 | /** Returns if the word is in the trie. */
25 | fun search(word: String): Boolean {
26 | var p = trieTree
27 |
28 | for (w in word) {
29 | val i = w - 'a'
30 | if (p.children[i] == null) return false
31 | p = p.children[i]!!
32 | }
33 | return p.isWord
34 | }
35 |
36 | /** Returns if there is any word in the trie that starts with the given prefix. */
37 | fun startsWith(prefix: String): Boolean {
38 | var p = trieTree
39 |
40 | for (w in prefix) {
41 | val i = w - 'a'
42 | if (p.children[i] == null) return false
43 | p = p.children[i]!!
44 | }
45 |
46 | return true
47 | }
48 |
49 | }
--------------------------------------------------------------------------------
/src/dynamicprogramming/ClimbingStairs.kt:
--------------------------------------------------------------------------------
1 | package dynamicprogramming
2 |
3 | class ClimbingStairs {
4 | fun climbingStairs(n: Int): Int {
5 | if (n <= 3) return n
6 | var one = 1
7 | var two = 2
8 | var result = one + two
9 | for (i in 3..n) {
10 | result = one + two
11 | one = two
12 | two = result
13 | }
14 | return result
15 | }
16 |
17 | private val dp = IntArray(10000) { -1 }
18 | fun knappSnackProblem(n: Int): Int {
19 | // 1 , 3 , 5
20 | if (n < 0) return 0
21 | if (n == 0) return 1
22 | if (dp[n] != -1) {
23 | return dp[n]
24 | }
25 | dp[n] = knappSnackProblem(n - 1) + knappSnackProblem(n - 3) + knappSnackProblem(n - 5)
26 | return dp[n]
27 | }
28 | }
29 |
30 | fun main() {
31 | val result = ClimbingStairs().knappSnackProblem(9)
32 | println(result)
33 | }
--------------------------------------------------------------------------------
/src/dynamicprogramming/EditDistance.kt:
--------------------------------------------------------------------------------
1 | package dynamicprogramming
2 |
3 | class EditDistance {
4 | fun minDistance(word1: String, word2: String): Int {
5 |
6 | val dp = Array(word1.length + 1) { IntArray(word2.length + 1) { 0 } }
7 | for (i in dp.indices) {
8 | for (j in dp[i].indices) {
9 | when {
10 | i == 0 -> {
11 | dp[i][j] = j
12 | }
13 | j == 0 -> {
14 | dp[i][j] = i
15 | }
16 | word1[i - 1] == word2[j - 1] -> {
17 | dp[i][j] = dp[i - 1][j - 1]
18 | }
19 | else -> {
20 | dp[i][j] = minOf(dp[i][j - 1], dp[i - 1][j - 1], dp[i - 1][j]) + 1
21 | }
22 | }
23 | }
24 | }
25 |
26 | repeat(dp.count()) {
27 | println(dp[it].contentToString())
28 | }
29 |
30 | return dp[dp.size - 1][dp[0].size - 1]
31 | }
32 |
33 | fun editDistDP(
34 | str1: String, str2: String, m: Int,
35 | n: Int
36 | ): Int { // Create a table to store results of subproblems
37 | val dp = Array(m + 1) { IntArray(n + 1) }
38 | // Fill d[][] in bottom up manner
39 | for (i in 0..m) {
40 | for (j in 0..n) {
41 | when {
42 | i == 0 -> dp[i][j] = j
43 | j == 0 -> dp[i][j] = i
44 | str1[i - 1] == str2[j - 1] -> dp[i][j] = dp[i - 1][j - 1]
45 | else -> dp[i][j] = (1 + minOf(
46 | dp[i][j - 1], dp[i - 1][j], dp[i - 1][j - 1]
47 | ))
48 | }
49 | }
50 | }
51 |
52 | repeat(dp.count()) {
53 | println(dp[it].contentToString())
54 | }
55 | return dp[m][n]
56 | }
57 | }
58 |
59 | fun main() {
60 | val str1 = "zoologicoarchaeologist"
61 | val str2 = "zoogeologist"
62 | val result = EditDistance().minDistance(str1, str2)
63 | println("result 2")
64 | val result2 = EditDistance().editDistDP(str1, str2, str1.length, str2.length)
65 |
66 | }
--------------------------------------------------------------------------------
/src/dynamicprogramming/Fibonacci.kt:
--------------------------------------------------------------------------------
1 | package dynamicprogramming
2 |
3 | class Fibonacci {
4 |
5 | private val lookupTable: IntArray = IntArray(40) { -1 }
6 |
7 | fun fibRecursive(n: Int): Int {
8 | if (n <= 1) {
9 | return n
10 | }
11 | return fibRecursive(n - 1) + fibRecursive(n - 2)
12 | }
13 |
14 | // overlapping sub problem
15 | fun fib(n: Int): Int {
16 | if (lookupTable[n] == -1) {
17 | if (n <= 1) {
18 | lookupTable[n] = n
19 | } else {
20 | lookupTable[n] = fib(n - 1) + fib(n - 2)
21 | }
22 | }
23 |
24 | return lookupTable[n]
25 | }
26 | }
27 |
28 | fun main() {
29 | println(Fibonacci().fibRecursive(6))
30 | println(Fibonacci().fib(6))
31 | }
--------------------------------------------------------------------------------
/src/dynamicprogramming/LongestValidParenthesis.kt:
--------------------------------------------------------------------------------
1 | package dynamicprogramming
2 |
3 | class LongestValidParenthesis {
4 |
5 | fun longestValidParentheses(s: String): Int {
6 | var maxans = 0
7 | val dp = IntArray(s.length)
8 | for (i in 1 until s.length) {
9 | // ( ) ) ( ( ( ) )
10 | // 0 0 0 0 0 0 0 0
11 | // 0 2 0 0 0 0 2
12 | if (s[i] == ')') {
13 | if (s[i - 1] == '(') {
14 | // i = 5
15 | dp[i] = (if (i >= 2) dp[i - 2] else 0) + 2
16 |
17 | } else if (i - dp[i - 1] > 0 && s[i - dp[i - 1] - 1] == '(') { // i= 7, 7 > 2 = &&s[ 7 - 2 - 1] , s[4] == '('
18 |
19 | dp[i] =
20 | dp[i - 1] + (if (i - dp[i - 1] >= 2) dp[i - dp[i - 1] - 2] else 0) + 2
21 | // 7 - 1 + 7 - 2 , dp[ 7 - 2 - 2] + 2
22 | // 4 .
23 |
24 | }
25 | maxans = maxOf(maxans, dp[i])
26 | }
27 | }
28 | return maxans
29 | }
30 |
31 | }
32 |
33 | fun main() {
34 | val longestValidParenthesis = LongestValidParenthesis()
35 | .longestValidParentheses("()()")
36 | println(longestValidParenthesis)
37 |
38 | }
--------------------------------------------------------------------------------
/src/dynamicprogramming/MinimumPathSum.kt:
--------------------------------------------------------------------------------
1 | package dynamicprogramming
2 |
3 | class MinimumPathSum {
4 | fun minPathSum(grid: Array): Int {
5 | val m = grid.size
6 | val n = grid[0].size
7 | val dp = Array(m) { Array(n) { 0 } }
8 |
9 | for (i in 0 until m) {
10 | for (j in 0 until n) {
11 | if (i == 0 && j == 0) {
12 | dp[i][j] = grid[i][j]
13 | } else if (i == 0) {
14 | dp[i][j] = dp[i][j - 1] + grid[i][j]
15 | } else if (j == 0) {
16 | dp[i][j] = dp[i - 1][j] + grid[i][j]
17 | } else {
18 | dp[i][j] = minOf(dp[i][j - 1], dp[i - 1][j]) + grid[i][j]
19 | }
20 | }
21 | }
22 | return dp[m - 1][n - 1]
23 | }
24 |
25 | }
26 |
27 | fun main() {
28 | // [[1,3,1],[1,5,1],[4,2,1]]
29 | println(
30 | MinimumPathSum().minPathSum(
31 | arrayOf(
32 | intArrayOf(1, 3, 1), intArrayOf(1, 5, 1),
33 | intArrayOf(4, 2, 1)
34 | )
35 | )
36 | )
37 | }
--------------------------------------------------------------------------------
/src/dynamicprogramming/NewStoneGame.kt:
--------------------------------------------------------------------------------
1 | package dynamicprogramming
2 |
3 | class NewStoneGame {
4 | fun stoneGameVII(stones: IntArray): Int {
5 | val sum = stones.sum()
6 | val memo = Array(stones.size){IntArray(stones.size){-1} }
7 | return play(stones, 0, stones.lastIndex, sum, memo)
8 | }
9 |
10 | fun play(stones: IntArray, l:Int, r: Int, sum: Int, memo: Array) : Int {
11 | if(l == r) return 0
12 | if (memo[l][r] != -1) return memo[l][r]
13 | val a = sum - stones[l] - play(stones, l+1, r, sum - stones[l], memo)
14 | val b = sum - stones[r] - play(stones, l, r-1, sum - stones[r], memo)
15 | memo[l][r] = maxOf(a, b)
16 | return memo[l][r]
17 | }
18 | }
19 |
20 | fun main() {
21 | val newStoneGame = NewStoneGame()
22 | val result = newStoneGame.stoneGameVII(intArrayOf(5, 3, 1, 4, 2))
23 | println(result)
24 | }
--------------------------------------------------------------------------------
/src/dynamicprogramming/PascalTriAngel.kt:
--------------------------------------------------------------------------------
1 | package dynamicprogramming
2 |
3 | class PascalTriAngel {
4 | fun getRow(numRows: Int): List {
5 | val result = mutableListOf>()
6 | result.add(mutableListOf(1))
7 | if (numRows == 1) return listOf(1, 1)
8 | result.add(mutableListOf(1, 1))
9 | if (numRows == 2) return listOf(1, 2, 1)
10 |
11 | for (i in 2..numRows) {
12 | val temp = mutableListOf()
13 | for (j in 0..i) {
14 | when (j) {
15 | 0 -> temp.add(1)
16 | i -> temp.add(1)
17 | else -> temp.add(result[i - 1][j] + result[i - 1][j - 1])
18 | }
19 | }
20 | result.add(temp)
21 | }
22 | return result[numRows].toList()
23 | }
24 | }
--------------------------------------------------------------------------------
/src/dynamicprogramming/RobberHouse.kt:
--------------------------------------------------------------------------------
1 | package dynamicprogramming
2 |
3 | class RobberHouse {
4 | fun rob(nums: IntArray): Int {
5 | var dp = nums.clone()
6 |
7 | // not consider the last
8 | for (i in 0..nums.size - 2) {
9 | for (j in i + 2..nums.size - 2) {
10 | dp[j] = maxOf(dp[j], nums[j] + dp[i])
11 | }
12 | }
13 |
14 | var maxI = 0
15 | dp.forEach {
16 | maxI = maxOf(it, maxI)
17 | }
18 |
19 | dp = nums.clone()
20 | for (i in 1 until nums.size) {
21 | for (j in i + 2 until nums.size) {
22 | dp[j] = maxOf(dp[j], nums[j] + dp[i])
23 | }
24 | }
25 | maxI = maxOf(dp.maxOrNull() as Int, maxI)
26 | return maxI
27 | }
28 |
29 | fun rob1(nums: IntArray): Int {
30 | val dp = nums.clone()
31 |
32 | // not consider the last
33 | for (i in nums.indices) {
34 | for (j in i + 2 until nums.size) {
35 | dp[j] = maxOf(dp[j], nums[j] + dp[i])
36 | println(dp[j])
37 | println(i)
38 | }
39 | }
40 | println(dp.contentToString())
41 |
42 | var maxI = 0
43 | dp.forEach {
44 | maxI = maxOf(it, maxI)
45 | }
46 | return maxI
47 | }
48 | }
49 |
50 | fun main() {
51 | val robberHouse = RobberHouse()
52 | println("result " + robberHouse.rob1(intArrayOf(2, 1, 1, 2)))
53 |
54 | }
--------------------------------------------------------------------------------
/src/dynamicprogramming/UniquePath.kt:
--------------------------------------------------------------------------------
1 | package dynamicprogramming
2 |
3 | class UniquePath {
4 | fun solution(m: Int, n: Int): Int {
5 | val dp = Array(m + 1) { IntArray(n + 1) { 0 } }
6 | val indexM = m - 1
7 | val indexN = n - 1
8 | for (i in indexM downTo 0) {
9 | for (j in indexN downTo 0) {
10 | if (i == indexM && j == indexN) {
11 | dp[i][j] = 1
12 | } else {
13 | dp[i][j] = dp[i + 1][j] + dp[i][j + 1]
14 | }
15 | }
16 | }
17 | return dp[0][0]
18 | }
19 | }
20 |
21 | fun main() {
22 | val solution = UniquePath().solution(4, 4)
23 | println(solution)
24 | }
--------------------------------------------------------------------------------
/src/hackerrank/ThePowerOfSum.kt:
--------------------------------------------------------------------------------
1 | package hackerrank
2 |
3 | import kotlin.math.pow
4 |
5 |
6 | fun powerSum(X: Int, N: Int): Int {
7 | return helper(X, N, 1)
8 | }
9 |
10 | fun helper(total: Int, power: Int, number: Int): Int {
11 | val value = total - number.toDouble().pow(power).toInt()
12 | if (value == 0) return 1
13 | if (value < 0) return 0
14 | return helper(value, power, number + 1) + helper(total, power, number + 1)
15 | }
16 |
17 | fun main() {
18 | println(powerSum(13, 2))
19 | }
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/BestTimeToBuyAndSellStockIi.kt:
--------------------------------------------------------------------------------
1 | //You are given an integer array prices where prices[i] is the price of a given
2 | //stock on the iᵗʰ day.
3 | //
4 | // On each day, you may decide to buy and/or sell the stock. You can only hold
5 | //at most one share of the stock at any time. However, you can buy it then
6 | //immediately sell it on the same day.
7 | //
8 | // Find and return the maximum profit you can achieve.
9 | //
10 | //
11 | // Example 1:
12 | //
13 | //
14 | //Input: prices = [7,1,5,3,6,4]
15 | //Output: 7
16 | //Explanation: Buy on day 2 (price = 1) and sell on day 3 (price = 5), profit =
17 | //5-1 = 4.
18 | //Then buy on day 4 (price = 3) and sell on day 5 (price = 6), profit = 6-3 = 3.
19 | //
20 | //Total profit is 4 + 3 = 7.
21 | //
22 | //
23 | // Example 2:
24 | //
25 | //
26 | //Input: prices = [1,2,3,4,5]
27 | //Output: 4
28 | //Explanation: Buy on day 1 (price = 1) and sell on day 5 (price = 5), profit =
29 | //5-1 = 4.
30 | //Total profit is 4.
31 | //
32 | //
33 | // Example 3:
34 | //
35 | //
36 | //Input: prices = [7,6,4,3,1]
37 | //Output: 0
38 | //Explanation: There is no way to make a positive profit, so we never buy the
39 | //stock to achieve the maximum profit of 0.
40 | //
41 | //
42 | //
43 | // Constraints:
44 | //
45 | //
46 | // 1 <= prices.length <= 3 * 10⁴
47 | // 0 <= prices[i] <= 10⁴
48 | //
49 | // Related Topics Array Dynamic Programming Greedy 👍 5910 👎 2234
50 |
51 |
52 | package leetcodeProblem.leetcode.editor.en
53 |
54 | class BestTimeToBuyAndSellStockIi {
55 | fun solution() {
56 | }
57 |
58 | //below code will be used for submission to leetcode (using plugin of course)
59 | //leetcode submit region begin(Prohibit modification and deletion)
60 | class Solution {
61 | fun maxProfit(prices: IntArray): Int {
62 | var maxProfit = 0
63 | for (i in 1 until prices.size) {
64 | maxProfit = maxOf(maxProfit, prices[i] - prices[i - 1] + maxProfit)
65 | }
66 | return maxProfit
67 | }
68 | }
69 | //leetcode submit region end(Prohibit modification and deletion)
70 |
71 | }
72 |
73 | fun main() {}
74 |
75 |
76 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/BestTimeToBuyAndSellStockWithTransactionFee.kt:
--------------------------------------------------------------------------------
1 | //You are given an array prices where prices[i] is the price of a given stock
2 | //on the iᵗʰ day, and an integer fee representing a transaction fee.
3 | //
4 | // Find the maximum profit you can achieve. You may complete as many
5 | //transactions as you like, but you need to pay the transaction fee for each transaction.
6 | //
7 | // Note: You may not engage in multiple transactions simultaneously (i.e., you
8 | //must sell the stock before you buy again).
9 | //
10 | //
11 | // Example 1:
12 | //
13 | //
14 | //Input: prices = [1,3,2,8,4,9], fee = 2
15 | //Output: 8
16 | //Explanation: The maximum profit can be achieved by:
17 | //- Buying at prices[0] = 1
18 | //- Selling at prices[3] = 8
19 | //- Buying at prices[4] = 4
20 | //- Selling at prices[5] = 9
21 | //The total profit is ((8 - 1) - 2) + ((9 - 4) - 2) = 8.
22 | //
23 | //
24 | // Example 2:
25 | //
26 | //
27 | //Input: prices = [1,3,7,5,10,3], fee = 3
28 | //Output: 6
29 | //
30 | //
31 | //
32 | // Constraints:
33 | //
34 | //
35 | // 1 <= prices.length <= 5 * 10⁴
36 | // 1 <= prices[i] < 5 * 10⁴
37 | // 0 <= fee < 5 * 10⁴
38 | //
39 | // Related Topics Array Dynamic Programming Greedy 👍 3117 👎 84
40 |
41 |
42 | package leetcodeProblem.leetcode.editor.en
43 |
44 | class BestTimeToBuyAndSellStockWithTransactionFee {
45 |
46 |
47 | //below code will be used for submission to leetcode (using plugin of course)
48 | //leetcode submit region begin(Prohibit modification and deletion)
49 | class Solution {
50 | fun maxProfit(prices: IntArray, fee: Int): Int {
51 | var cash = 0
52 | var hold = -prices[0]
53 | for (i in 1 until prices.size) {
54 | cash = maxOf(cash, hold + prices[i] - fee)
55 | hold = maxOf(hold, cash - prices[i])
56 | }
57 | return cash
58 | }
59 |
60 | }
61 | //leetcode submit region end(Prohibit modification and deletion)
62 |
63 | }
64 |
65 | fun main() {
66 | println(BestTimeToBuyAndSellStockWithTransactionFee.Solution().maxProfit(intArrayOf(1, 3, 2, 8, 4, 9), 2))
67 | }
68 |
69 |
70 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/BinaryTreeInorderTraversal.kt:
--------------------------------------------------------------------------------
1 | //Given the root of a binary tree, return the inorder traversal of its nodes'
2 | //values.
3 | //
4 | //
5 | // Example 1:
6 | //
7 | //
8 | //Input: root = [1,null,2,3]
9 | //Output: [1,3,2]
10 | //
11 | //
12 | // Example 2:
13 | //
14 | //
15 | //Input: root = []
16 | //Output: []
17 | //
18 | //
19 | // Example 3:
20 | //
21 | //
22 | //Input: root = [1]
23 | //Output: [1]
24 | //
25 | //
26 | // Example 4:
27 | //
28 | //
29 | //Input: root = [1,2]
30 | //Output: [2,1]
31 | //
32 | //
33 | // Example 5:
34 | //
35 | //
36 | //Input: root = [1,null,2]
37 | //Output: [1,2]
38 | //
39 | //
40 | //
41 | // Constraints:
42 | //
43 | //
44 | // The number of nodes in the tree is in the range [0, 100].
45 | // -100 <= Node.val <= 100
46 | //
47 | //
48 | //
49 | //Follow up: Recursive solution is trivial, could you do it iteratively?
50 | //Related Topics Stack Tree Depth-First Search Binary Tree 👍 6150 👎 259
51 |
52 |
53 | package leetcodeProblem.leetcode.editor.en
54 |
55 | import data_structure.tree.TreeNode
56 | import java.util.*
57 |
58 |
59 | class BinaryTreeInorderTraversal {
60 | fun solution() {
61 | }
62 | //below code will be used for submission to leetcode (using plugin of course)
63 | //leetcode submit region begin(Prohibit modification and deletion)
64 | /**
65 | * Example:
66 | * var ti = TreeNode(5)
67 | * var v = ti.`val`
68 | * Definition for a binary tree node.
69 | * class TreeNode(var `val`: Int) {
70 | * var left: TreeNode? = null
71 | * var right: TreeNode? = nullg
72 | * }
73 | */
74 | class Solution {
75 | private val listInOrder = mutableListOf()
76 | fun inorderTraversal(root: TreeNode?): List {
77 |
78 | fun recursive(r1: TreeNode?) {
79 | if (r1 == null) return
80 | if (r1.left != null) {
81 | recursive(r1.left)
82 | }
83 | listInOrder.add(r1.value)
84 | if (r1.right != null) {
85 | recursive(r1.right)
86 | }
87 | }
88 |
89 | fun iterative(r2: TreeNode?) {
90 | val stack = Stack()
91 | var curr = r2
92 | while (curr != null || !stack.isEmpty()) {
93 | while (curr != null) {
94 | stack.push(curr)
95 | curr = curr.left
96 | }
97 | curr = stack.pop()
98 | listInOrder.add(curr.value)
99 | curr = curr.right
100 | }
101 | }
102 |
103 | iterative(root)
104 |
105 | return listInOrder
106 | }
107 | }
108 |
109 |
110 | //leetcode submit region end(Prohibit modification and deletion)
111 |
112 | }
113 |
114 | fun main() {}
115 |
116 |
117 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/ContainsDuplicate.kt:
--------------------------------------------------------------------------------
1 | //Given an integer array nums, return true if any value appears at least twice
2 | //in the array, and return false if every element is distinct.
3 | //
4 | //
5 | // Example 1:
6 | // Input: nums = [1,2,3,1]
7 | //Output: true
8 | // Example 2:
9 | // Input: nums = [1,2,3,4]
10 | //Output: false
11 | // Example 3:
12 | // Input: nums = [1,1,1,3,3,4,3,2,4,2]
13 | //Output: true
14 | //
15 | //
16 | // Constraints:
17 | //
18 | //
19 | // 1 <= nums.length <= 10⁵
20 | // -10⁹ <= nums[i] <= 10⁹
21 | //
22 | // Related Topics Array Hash Table Sorting 👍 2676 👎 891
23 |
24 |
25 | package leetcodeProblem.leetcode.editor.en
26 |
27 | class ContainsDuplicate {
28 | fun solution() {
29 | }
30 |
31 | //below code will be used for submission to leetcode (using plugin of course)
32 | //leetcode submit region begin(Prohibit modification and deletion)
33 | class Solution {
34 | fun containsDuplicate(nums: IntArray): Boolean {
35 | val hashMap: HashMap = HashMap()
36 | for (i in nums.indices) {
37 | if (hashMap.containsKey(nums[i])) return true else hashMap[nums[i]] = 1
38 | }
39 |
40 | return false
41 | }
42 | }
43 | //leetcode submit region end(Prohibit modification and deletion)
44 |
45 | }
46 |
47 | fun main() {}
48 |
49 |
50 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/FindAllNumbersDisappearedInAnArray.kt:
--------------------------------------------------------------------------------
1 | //Given an array nums of n integers where nums[i] is in the range [1, n],
2 | //return an array of all the integers in the range [1, n] that do not appear in nums.
3 | //
4 | //
5 | // Example 1:
6 | // Input: nums = [4,3,2,7,8,2,3,1]
7 | //Output: [5,6]
8 | // Example 2:
9 | // Input: nums = [1,1]
10 | //Output: [2]
11 | //
12 | //
13 | // Constraints:
14 | //
15 | //
16 | // n == nums.length
17 | // 1 <= n <= 10⁵
18 | // 1 <= nums[i] <= n
19 | //
20 | //
21 | //
22 | // Follow up: Could you do it without extra space and in O(n) runtime? You may
23 | //assume the returned list does not count as extra space.
24 | // Related Topics Array Hash Table 👍 5425 👎 345
25 |
26 |
27 | package leetcodeProblem.leetcode.editor.en
28 |
29 | class FindAllNumbersDisappearedInAnArray {
30 | fun solution() {
31 | }
32 |
33 | //below code will be used for submission to leetcode (using plugin of course)
34 | //leetcode submit region begin(Prohibit modification and deletion)
35 | class Solution {
36 | fun findDisappearedNumbers(nums: IntArray): List {
37 | val n = nums.size
38 | val list = mutableListOf()
39 | for (i in 1..n) {
40 | if (!nums.contains(i)) {
41 | list.add(i)
42 | }
43 | }
44 | return list
45 | }
46 | }
47 | //leetcode submit region end(Prohibit modification and deletion)
48 |
49 | }
50 |
51 | fun main() {}
52 |
53 |
54 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/FindFirstAndLastPositionOfElementInSortedArray.kt:
--------------------------------------------------------------------------------
1 | //Given an array of integers nums sorted in non-decreasing order, find the
2 | //starting and ending position of a given target value.
3 | //
4 | // If target is not found in the array, return [-1, -1].
5 | //
6 | // You must write an algorithm with O(log n) runtime complexity.
7 | //
8 | //
9 | // Example 1:
10 | // Input: nums = [5,7,7,8,8,10], target = 8
11 | //Output: [3,4]
12 | // Example 2:
13 | // Input: nums = [5,7,7,8,8,10], target = 6
14 | //Output: [-1,-1]
15 | // Example 3:
16 | // Input: nums = [], target = 0
17 | //Output: [-1,-1]
18 | //
19 | //
20 | // Constraints:
21 | //
22 | //
23 | // 0 <= nums.length <= 10⁵
24 | // -10⁹ <= nums[i] <= 10⁹
25 | // nums is a non-decreasing array.
26 | // -10⁹ <= target <= 10⁹
27 | //
28 | // Related Topics Array Binary Search 👍 7758 👎 246
29 |
30 |
31 | package leetcodeProblem.leetcode.editor.en
32 |
33 | class FindFirstAndLastPositionOfElementInSortedArray {
34 | fun solution() {
35 | }
36 |
37 | //below code will be used for submission to leetcode (using plugin of course)
38 | //leetcode submit region begin(Prohibit modification and deletion)
39 | class Solution {
40 | fun searchRange(nums: IntArray, target: Int): IntArray {
41 | var findFirst = -1
42 | var findLast = -1
43 | var l = 0
44 | var r = nums.size - 1
45 | while (l <= r) {
46 | val middle = l + (r - l) / 2
47 | if (nums[middle] == target) {
48 | for (i in middle..nums.size) {
49 | if (nums[i] != target) {
50 | findLast = i - 1
51 | break
52 | }
53 | }
54 | for (i in middle downTo 0) {
55 | if (nums[i] != target) {
56 | findFirst = i + 1
57 | break
58 | }
59 | }
60 | break
61 | } else if (nums[middle] > target) {
62 | r = middle - 1
63 | } else {
64 | l = middle + 1
65 | }
66 | }
67 | return intArrayOf(findFirst, findLast)
68 | }
69 | }
70 | //leetcode submit region end(Prohibit modification and deletion)
71 |
72 | }
73 |
74 | fun main() {
75 | FindFirstAndLastPositionOfElementInSortedArray.Solution().searchRange(intArrayOf(5, 7, 7, 8, 8, 10), 8)
76 | }
77 |
78 |
79 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/HammingDistance.kt:
--------------------------------------------------------------------------------
1 | //The Hamming distance between two integers is the number of positions at which
2 | //the corresponding bits are different.
3 | //
4 | // Given two integers x and y, return the Hamming distance between them.
5 | //
6 | //
7 | // Example 1:
8 | //
9 | //
10 | //Input: x = 1, y = 4
11 | //Output: 2
12 | //Explanation:
13 | //1 (0 0 0 1)
14 | //4 (0 1 0 0)
15 | // ↑ ↑
16 | //The above arrows point to positions where the corresponding bits are
17 | //different.
18 | //
19 | //
20 | // Example 2:
21 | //
22 | //
23 | //Input: x = 3, y = 1
24 | //Output: 1
25 | //
26 | //
27 | //
28 | // Constraints:
29 | //
30 | //
31 | // 0 <= x, y <= 2³¹ - 1
32 | //
33 | // Related Topics Bit Manipulation 👍 2642 👎 188
34 |
35 |
36 | package leetcodeProblem.leetcode.editor.en
37 |
38 | class HammingDistance {
39 | fun solution() {
40 | }
41 |
42 | //below code will be used for submission to leetcode (using plugin of course)
43 | //leetcode submit region begin(Prohibit modification and deletion)
44 | class Solution {
45 | fun oneLineHammingDistance(x: Int, y: Int): Int {
46 | return Integer.bitCount(x xor y)
47 | }
48 |
49 | fun hammingDistance(x: Int, y: Int): Int {
50 | if (x == y) return 0
51 | var count = 0
52 | var n = x xor y
53 | while (n > 0) {
54 | count += n and 1
55 | n = n shr 1
56 | }
57 | return count
58 | }
59 | }
60 | //leetcode submit region end(Prohibit modification and deletion)
61 |
62 | }
63 |
64 | fun main() {
65 | HammingDistance.Solution().hammingDistance(11, 12)
66 | }
67 |
68 |
69 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/LargestDivisibleSubset.kt:
--------------------------------------------------------------------------------
1 | //Given a set of distinct positive integers nums, return the largest subset
2 | //answer such that every pair (answer[i], answer[j]) of elements in this subset
3 | //satisfies:
4 | //
5 | //
6 | // answer[i] % answer[j] == 0, or
7 | // answer[j] % answer[i] == 0
8 | //
9 | //
10 | // If there are multiple solutions, return any of them.
11 | //
12 | //
13 | // Example 1:
14 | //
15 | //
16 | //Input: nums = [1,2,3]
17 | //Output: [1,2]
18 | //Explanation: [1,3] is also accepted.
19 | //
20 | //
21 | // Example 2:
22 | //
23 | //
24 | //Input: nums = [1,2,4,8]
25 | //Output: [1,2,4,8]
26 | //
27 | //
28 | //
29 | // Constraints:
30 | //
31 | //
32 | // 1 <= nums.length <= 1000
33 | // 1 <= nums[i] <= 2 * 10⁹
34 | // All the integers in nums are unique.
35 | //
36 | // Related Topics Array Math Dynamic Programming Sorting 👍 2270 👎 105
37 |
38 |
39 | package leetcodeProblem.leetcode.editor.en
40 |
41 | import java.util.*
42 |
43 |
44 | class LargestDivisibleSubset {
45 | fun solution() {
46 | }
47 |
48 | //below code will be used for submission to leetcode (using plugin of course)
49 | //leetcode submit region begin(Prohibit modification and deletion)
50 | class Solution {
51 | fun largestDivisibleSubset(nums: IntArray): List {
52 | val n = nums.size
53 | val count = IntArray(n)
54 | val pre = IntArray(n)
55 | Arrays.sort(nums)
56 | var max = 0
57 | var index = -1
58 | for (i in 0 until n) {
59 | count[i] = 1
60 | pre[i] = -1
61 | for (j in i - 1 downTo 0) {
62 | if (nums[i] % nums[j] == 0) {
63 | if (1 + count[j] > count[i]) {
64 | count[i] = count[j] + 1
65 | pre[i] = j
66 | }
67 | }
68 | }
69 | if (count[i] > max) {
70 | max = count[i]
71 | index = i
72 | }
73 | }
74 | val res: MutableList = ArrayList()
75 | while (index != -1) {
76 | res.add(nums[index])
77 | index = pre[index]
78 | }
79 | return res
80 | }
81 | }
82 | //leetcode submit region end(Prohibit modification and deletion)
83 |
84 | }
85 |
86 | fun main() {
87 | println(
88 | LargestDivisibleSubset.Solution().largestDivisibleSubset(intArrayOf(4, 8, 10, 240))
89 | )
90 | }
91 |
92 |
93 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/LongestIncreasingSubsequence.kt:
--------------------------------------------------------------------------------
1 | //Given an integer array nums, return the length of the longest strictly
2 | //increasing subsequence.
3 | //
4 | // A subsequence is a sequence that can be derived from an array by deleting
5 | //some or no elements without changing the order of the remaining elements. For
6 | //example, [3,6,2,7] is a subsequence of the array [0,3,1,6,2,2,7].
7 | //
8 | //
9 | // Example 1:
10 | //
11 | //
12 | //Input: nums = [10,9,2,5,3,7,101,18]
13 | //Output: 4
14 | //Explanation: The longest increasing subsequence is [2,3,7,101], therefore the
15 | //length is 4.
16 | //
17 | //
18 | // Example 2:
19 | //
20 | //
21 | //Input: nums = [0,1,0,3,2,3]
22 | //Output: 4
23 | //
24 | //
25 | // Example 3:
26 | //
27 | //
28 | //Input: nums = [7,7,7,7,7,7,7]
29 | //Output: 1
30 | //
31 | //
32 | //
33 | // Constraints:
34 | //
35 | //
36 | // 1 <= nums.length <= 2500
37 | // -10⁴ <= nums[i] <= 10⁴
38 | //
39 | //
40 | //
41 | // Follow up: Can you come up with an algorithm that runs in O(n log(n)) time
42 | //complexity?
43 | // Related Topics Array Binary Search Dynamic Programming 👍 9353 👎 192
44 |
45 |
46 | package leetcodeProblem.leetcode.editor.en
47 |
48 | class LongestIncreasingSubsequence {
49 | fun solution() {
50 | }
51 |
52 | //below code will be used for submission to leetcode (using plugin of course)
53 | //leetcode submit region begin(Prohibit modification and deletion)
54 | class Solution {
55 | fun lengthOfLIS(nums: IntArray): Int {
56 | val dp = IntArray(nums.size) { 1 }
57 | var max = Int.MIN_VALUE
58 | for (i in 1 until nums.size) {
59 | for (j in 0..i) {
60 | if (nums[i] > nums[j] && dp[i] < dp[j] + 1) {
61 | dp[i] = dp[j] + 1
62 | }
63 | }
64 | max = maxOf(max, dp[i])
65 | }
66 | println(dp.contentToString())
67 | return max
68 | }
69 | }
70 | //leetcode submit region end(Prohibit modification and deletion)
71 |
72 | }
73 |
74 | fun main() {
75 | println(LongestIncreasingSubsequence.Solution().lengthOfLIS(intArrayOf(10,9,2,5,3,7,101,18)))
76 | }
77 |
78 |
79 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/LongestSubstringWithoutRepeatingCharacters.kt:
--------------------------------------------------------------------------------
1 | //Given a string s, find the length of the longest substring without repeating
2 | //characters.
3 | //
4 | //
5 | // Example 1:
6 | //
7 | //
8 | //Input: s = "abcabcbb"
9 | //Output: 3
10 | //Explanation: The answer is "abc", with the length of 3.
11 | //
12 | //
13 | // Example 2:
14 | //
15 | //
16 | //Input: s = "bbbbb"
17 | //Output: 1
18 | //Explanation: The answer is "b", with the length of 1.
19 | //
20 | //
21 | // Example 3:
22 | //
23 | //
24 | //Input: s = "pwwkew"
25 | //Output: 3
26 | //Explanation: The answer is "wke", with the length of 3.
27 | //Notice that the answer must be a substring, "pwke" is a subsequence and not a
28 | //substring.
29 | //
30 | //
31 | // Example 4:
32 | //
33 | //
34 | //Input: s = ""
35 | //Output: 0
36 | //
37 | //
38 | //
39 | // Constraints:
40 | //
41 | //
42 | // 0 <= s.length <= 5 * 10⁴
43 | // s consists of English letters, digits, symbols and spaces.
44 | //
45 | // Related Topics Hash Table String Sliding Window 👍 18261 👎 839
46 |
47 |
48 | package leetcodeProblem.leetcode.editor.en
49 |
50 | class LongestSubstringWithoutRepeatingCharacters {
51 | fun solution() {
52 | }
53 |
54 | //below code will be used for submission to leetcode (using plugin of course)
55 | //leetcode submit region begin(Prohibit modification and deletion)
56 | class Solution {
57 | fun lengthOfLongestSubstring(s: String): Int {
58 | var longest = 0
59 | var currentRunStartIndex = 0
60 | val lastSeenIndices = IntArray(128)
61 | s.toCharArray().forEachIndexed { index, char ->
62 | with(char.toInt()) {
63 | currentRunStartIndex = maxOf(lastSeenIndices[this], currentRunStartIndex)
64 | longest = maxOf(longest, index - currentRunStartIndex + 1)
65 | lastSeenIndices[this] = index + 1
66 | }
67 | }
68 | return longest
69 | }
70 | }
71 | //leetcode submit region end(Prohibit modification and deletion)
72 |
73 | }
74 |
75 | fun main() {
76 |
77 | }
78 |
79 |
80 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/MaximumSubarray.kt:
--------------------------------------------------------------------------------
1 | //Given an integer array nums, find the contiguous subarray (containing at
2 | //least one number) which has the largest sum and return its sum.
3 | //
4 | // A subarray is a contiguous part of an array.
5 | //
6 | //
7 | // Example 1:
8 | //
9 | //
10 | //Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
11 | //Output: 6
12 | //Explanation: [4,-1,2,1] has the largest sum = 6.
13 | //
14 | //
15 | // Example 2:
16 | //
17 | //
18 | //Input: nums = [1]
19 | //Output: 1
20 | //
21 | //
22 | // Example 3:
23 | //
24 | //
25 | //Input: nums = [5,4,-1,7,8]
26 | //Output: 23
27 | //
28 | //
29 | //
30 | // Constraints:
31 | //
32 | //
33 | // 1 <= nums.length <= 10⁵
34 | // -10⁴ <= nums[i] <= 10⁴
35 | //
36 | //
37 | //
38 | // Follow up: If you have figured out the O(n) solution, try coding another
39 | //solution using the divide and conquer approach, which is more subtle.
40 | // Related Topics Array Divide and Conquer Dynamic Programming 👍 15318 👎 717
41 |
42 |
43 | package leetcodeProblem.leetcode.editor.en
44 |
45 | class MaximumSubarray {
46 | fun solution() {
47 | }
48 |
49 | //below code will be used for submission to leetcode (using plugin of course)
50 | //leetcode submit region begin(Prohibit modification and deletion)
51 | class Solution {
52 | fun maxSubArray(nums: IntArray): Int {
53 | var maxNow = Int.MIN_VALUE
54 | var current = 0
55 | nums.forEach {
56 | current = maxOf(current + it, it)
57 | maxNow = maxOf(current, maxNow)
58 | }
59 | return maxNow
60 | }
61 | }
62 | //leetcode submit region end(Prohibit modification and deletion)
63 |
64 | }
65 |
66 | fun main() {}
67 |
68 |
69 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/MinStack.kt:
--------------------------------------------------------------------------------
1 | //Design a stack that supports push, pop, top, and retrieving the minimum
2 | //element in constant time.
3 | //
4 | // Implement the MinStack class:
5 | //
6 | //
7 | // MinStack() initializes the stack object.
8 | // void push(int val) pushes the element val onto the stack.
9 | // void pop() removes the element on the top of the stack.
10 | // int top() gets the top element of the stack.
11 | // int getMin() retrieves the minimum element in the stack.
12 | //
13 | //
14 | //
15 | // Example 1:
16 | //
17 | //
18 | //Input
19 | //["MinStack","push","push","push","getMin","pop","top","getMin"]
20 | //[[],[-2],[0],[-3],[],[],[],[]]
21 | //
22 | //Output
23 | //[null,null,null,null,-3,null,0,-2]
24 | //
25 | //Explanation
26 | //MinStack minStack = new MinStack();
27 | //minStack.push(-2);
28 | //minStack.push(0);
29 | //minStack.push(-3);
30 | //minStack.getMin(); // return -3
31 | //minStack.pop();
32 | //minStack.top(); // return 0
33 | //minStack.getMin(); // return -2
34 | //
35 | //
36 | //
37 | // Constraints:
38 | //
39 | //
40 | // -2³¹ <= val <= 2³¹ - 1
41 | // Methods pop, top and getMin operations will always be called on non-empty
42 | //stacks.
43 | // At most 3 * 10⁴ calls will be made to push, pop, top, and getMin.
44 | //
45 | // Related Topics Stack Design 👍 6128 👎 538
46 |
47 |
48 | package leetcodeProblem.leetcode.editor.en
49 |
50 | import java.util.*
51 |
52 | class MinStack {
53 | fun solution() {
54 | }
55 |
56 | //below code will be used for submission to leetcode (using plugin of course)
57 | //leetcode submit region begin(Prohibit modification and deletion)
58 | class MinStack() {
59 | private val stack = Stack()
60 | private val minStack = Stack()
61 |
62 | fun push(x: Int) {
63 | stack.push(x)
64 |
65 | if (minStack.empty() || x <= minStack.peek()) {
66 | minStack.push(x)
67 | }
68 | }
69 |
70 | fun pop() {
71 | val el = stack.pop()
72 |
73 | if (!minStack.empty() && el == minStack.peek()) {
74 | minStack.pop()
75 | }
76 | }
77 |
78 | fun top(): Int {
79 | return stack.peek()
80 | }
81 |
82 | fun getMin(): Int {
83 | return minStack.peek()
84 | }
85 | }
86 |
87 | /**
88 | * Your MinStack object will be instantiated and called as such:
89 | * var obj = MinStack()
90 | * obj.push(`val`)
91 | * obj.pop()
92 | * var param_3 = obj.top()
93 | * var param_4 = obj.getMin()
94 | */
95 | //leetcode submit region end(Prohibit modification and deletion)
96 |
97 | }
98 |
99 | fun main() {}
100 |
101 |
102 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/MinimumRemoveToMakeValidParentheses.kt:
--------------------------------------------------------------------------------
1 | //Given a string s of '(' , ')' and lowercase English characters.
2 | //
3 | // Your task is to remove the minimum number of parentheses ( '(' or ')', in
4 | //any positions ) so that the resulting parentheses string is valid and return any
5 | //valid string.
6 | //
7 | // Formally, a parentheses string is valid if and only if:
8 | //
9 | //
10 | // It is the empty string, contains only lowercase characters, or
11 | // It can be written as AB (A concatenated with B), where A and B are valid
12 | //strings, or
13 | // It can be written as (A), where A is a valid string.
14 | //
15 | //
16 | //
17 | // Example 1:
18 | //
19 | //
20 | //Input: s = "lee(t(c)o)de)"
21 | //Output: "lee(t(c)o)de"
22 | //Explanation: "lee(t(co)de)" , "lee(t(c)ode)" would also be accepted.
23 | //
24 | //
25 | // Example 2:
26 | //
27 | //
28 | //Input: s = "a)b(c)d"
29 | //Output: "ab(c)d"
30 | //
31 | //
32 | // Example 3:
33 | //
34 | //
35 | //Input: s = "))(("
36 | //Output: ""
37 | //Explanation: An empty string is also valid.
38 | //
39 | //
40 | // Example 4:
41 | //
42 | //
43 | //Input: s = "(a(b(c)d)"
44 | //Output: "a(b(c)d)"
45 | //
46 | //
47 | //
48 | // Constraints:
49 | //
50 | //
51 | // 1 <= s.length <= 10⁵
52 | // s[i] is either'(' , ')', or lowercase English letter.
53 | //
54 | // Related Topics String Stack 👍 2786 👎 60
55 |
56 |
57 | package leetcodeProblem.leetcode.editor.en
58 |
59 |
60 | import java.util.*
61 | import kotlin.text.StringBuilder
62 |
63 | class MinimumRemoveToMakeValidParentheses {
64 | fun solution() {
65 | }
66 |
67 | //below code will be used for submission to leetcode (using plugin of course)
68 | //leetcode submit region begin(Prohibit modification and deletion)
69 | class Solution {
70 | fun minRemoveToMakeValid(s: String): String {
71 | val arr = s.toCharArray()
72 | val result = StringBuilder()
73 | val stack = Stack()
74 |
75 | for (i in s.indices) {
76 | val char = s[i]
77 | if (char == '(') {
78 | stack.push(i)
79 | } else if (char == ')') {
80 | if (stack.isNotEmpty()) stack.pop()
81 | else arr[i] = '~'
82 | }
83 | }
84 |
85 | while (stack.isNotEmpty()) {
86 | arr[stack.pop()] = '~'
87 | }
88 |
89 | arr.forEach { if (it != '~') result.append(it) }
90 |
91 | return result.toString()
92 | }
93 | }
94 | //leetcode submit region end(Prohibit modification and deletion)
95 |
96 | }
97 |
98 | fun main() {}
99 |
100 |
101 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/MissingNumber.kt:
--------------------------------------------------------------------------------
1 | //Given an array nums containing n distinct numbers in the range [0, n], return
2 | //the only number in the range that is missing from the array.
3 | //
4 | //
5 | // Example 1:
6 | //
7 | //
8 | //Input: nums = [3,0,1]
9 | //Output: 2
10 | //Explanation: n = 3 since there are 3 numbers, so all numbers are in the range
11 | //[0,3]. 2 is the missing number in the range since it does not appear in nums.
12 | //
13 | //
14 | // Example 2:
15 | //
16 | //
17 | //Input: nums = [0,1]
18 | //Output: 2
19 | //Explanation: n = 2 since there are 2 numbers, so all numbers are in the range
20 | //[0,2]. 2 is the missing number in the range since it does not appear in nums.
21 | //
22 | //
23 | // Example 3:
24 | //
25 | //
26 | //Input: nums = [9,6,4,2,3,5,7,0,1]
27 | //Output: 8
28 | //Explanation: n = 9 since there are 9 numbers, so all numbers are in the range
29 | //[0,9]. 8 is the missing number in the range since it does not appear in nums.
30 | //
31 | //
32 | // Example 4:
33 | //
34 | //
35 | //Input: nums = [0]
36 | //Output: 1
37 | //Explanation: n = 1 since there is 1 number, so all numbers are in the range [0
38 | //,1]. 1 is the missing number in the range since it does not appear in nums.
39 | //
40 | //
41 | //
42 | // Constraints:
43 | //
44 | //
45 | // n == nums.length
46 | // 1 <= n <= 10⁴
47 | // 0 <= nums[i] <= n
48 | // All the numbers of nums are unique.
49 | //
50 | //
51 | //
52 | // Follow up: Could you implement a solution using only O(1) extra space
53 | //complexity and O(n) runtime complexity?
54 | // Related Topics Array Hash Table Math Bit Manipulation Sorting 👍 4009 👎 2686
55 | //
56 |
57 |
58 | package leetcodeProblem.leetcode.editor.en
59 |
60 | class MissingNumber {
61 | fun solution() {
62 | }
63 |
64 | //below code will be used for submission to leetcode (using plugin of course)
65 | //leetcode submit region begin(Prohibit modification and deletion)
66 | class Solution {
67 | fun missingNumber(nums: IntArray): Int {
68 | val n = nums.size
69 | val total = n * (n + 1) / 2
70 | var sum = 0
71 | for (num in nums) {
72 | sum += num
73 | }
74 | return total - sum
75 | }
76 | }
77 | //leetcode submit region end(Prohibit modification and deletion)
78 |
79 | }
80 |
81 | fun main() {}
82 |
83 |
84 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/MoveZeroes.kt:
--------------------------------------------------------------------------------
1 | //Given an integer array nums, move all 0's to the end of it while maintaining
2 | //the relative order of the non-zero elements.
3 | //
4 | // Note that you must do this in-place without making a copy of the array.
5 | //
6 | //
7 | // Example 1:
8 | // Input: nums = [0,1,0,3,12]
9 | //Output: [1,3,12,0,0]
10 | // Example 2:
11 | // Input: nums = [0]
12 | //Output: [0]
13 | //
14 | //
15 | // Constraints:
16 | //
17 | //
18 | // 1 <= nums.length <= 10⁴
19 | // -2³¹ <= nums[i] <= 2³¹ - 1
20 | //
21 | //
22 | //
23 | //Follow up: Could you minimize the total number of operations done? Related
24 | //Topics Array Two Pointers 👍 6894 👎 193
25 |
26 |
27 | package leetcodeProblem.leetcode.editor.en
28 |
29 | class MoveZeroes {
30 | fun solution() {
31 | }
32 |
33 | //below code will be used for submission to leetcode (using plugin of course)
34 | //leetcode submit region begin(Prohibit modification and deletion)
35 | class Solution {
36 | fun moveZeroes(nums: IntArray) {
37 | var lastFoundZeroes = 0
38 | var pointer1 = 0
39 | while (pointer1 < nums.size) {
40 | if (nums[pointer1] != 0) {
41 | val temp = nums[pointer1]
42 | nums[pointer1] = nums[lastFoundZeroes]
43 | nums[lastFoundZeroes] = temp
44 | lastFoundZeroes++
45 | }
46 | println(nums.contentToString())
47 | pointer1++
48 | }
49 |
50 | }
51 | }
52 | //leetcode submit region end(Prohibit modification and deletion)
53 |
54 | }
55 |
56 | fun main() {
57 | MoveZeroes.Solution().moveZeroes(intArrayOf(0, 1, 0, 3, 12, 0, 0, 0, 1))
58 | }
59 |
60 |
61 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/MultiplyStrings.kt:
--------------------------------------------------------------------------------
1 | //Given two non-negative integers num1 and num2 represented as strings, return
2 | //the product of num1 and num2, also represented as a string.
3 | //
4 | // Note: You must not use any built-in BigInteger library or convert the inputs
5 | //to integer directly.
6 | //
7 | //
8 | // Example 1:
9 | // Input: num1 = "2", num2 = "3"
10 | //Output: "6"
11 | // Example 2:
12 | // Input: num1 = "123", num2 = "456"
13 | //Output: "56088"
14 | //
15 | //
16 | // Constraints:
17 | //
18 | //
19 | // 1 <= num1.length, num2.length <= 200
20 | // num1 and num2 consist of digits only.
21 | // Both num1 and num2 do not contain any leading zero, except the number 0
22 | //itself.
23 | //
24 | // Related Topics Math String Simulation 👍 3398 👎 1336
25 |
26 |
27 | package leetcodeProblem.leetcode.editor.en
28 |
29 | class MultiplyStrings {
30 | fun solution() {
31 | }
32 |
33 | //below code will be used for submission to leetcode (using plugin of course)
34 | //leetcode submit region begin(Prohibit modification and deletion)
35 | class Solution {
36 | fun multiply(num1: String, num2: String): String {
37 | if ("0" == num1 || "0" == num2)
38 | return "0"
39 |
40 | val list = Array(num1.length + num2.length - 1){0}
41 |
42 | for (i in num1.length - 1 downTo 0) {
43 | for (j in num2.length - 1 downTo 0) {
44 | list[i + j] += (num1[i] - '0') * (num2[j] - '0')
45 | }
46 | }
47 |
48 | for (i in list.size - 1 downTo 1) {
49 | list[i - 1] += list[i] / 10
50 | list[i] %= 10
51 | }
52 |
53 | val builder = StringBuilder()
54 | list.forEach {
55 | builder.append(it)
56 | }
57 |
58 | return builder.toString()
59 | }
60 | }
61 | //leetcode submit region end(Prohibit modification and deletion)
62 |
63 | }
64 |
65 | fun main() {}
66 |
67 |
68 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/NumberOfValidWordsForEachPuzzle.kt:
--------------------------------------------------------------------------------
1 | //With respect to a given puzzle string, a word is valid if both the following
2 | //conditions are satisfied:
3 | //
4 | // word contains the first letter of puzzle.
5 | // For each letter in word, that letter is in puzzle.
6 | //
7 | // For example, if the puzzle is "abcdefg", then valid words are "faced",
8 | //"cabbage", and "baggage", while
9 | // invalid words are "beefed" (does not include 'a') and "based" (includes 's'
10 | //which is not in the puzzle).
11 | //
12 | //
13 | //
14 | //Return an array answer, where answer[i] is the number of words in the given
15 | //word list words that is valid with respect to the puzzle puzzles[i].
16 | //
17 | // Example 1:
18 | //
19 | //
20 | //Input: words = ["aaaa","asas","able","ability","actt","actor","access"],
21 | //puzzles = ["aboveyz","abrodyz","abslute","absoryz","actresz","gaswxyz"]
22 | //Output: [1,1,3,2,4,0]
23 | //Explanation:
24 | //1 valid word for "aboveyz" : "aaaa"
25 | //1 valid word for "abrodyz" : "aaaa"
26 | //3 valid words for "abslute" : "aaaa", "asas", "able"
27 | //2 valid words for "absoryz" : "aaaa", "asas"
28 | //4 valid words for "actresz" : "aaaa", "asas", "actt", "access"
29 | //There are no valid words for "gaswxyz" cause none of the words in the list
30 | //contains letter 'g'.
31 | //
32 | //
33 | // Example 2:
34 | //
35 | //
36 | //Input: words = ["apple","pleas","please"], puzzles = ["aelwxyz","aelpxyz",
37 | //"aelpsxy","saelpxy","xaelpsy"]
38 | //Output: [0,1,3,2,0]
39 | //
40 | //
41 | //
42 | // Constraints:
43 | //
44 | //
45 | // 1 <= words.length <= 10⁵
46 | // 4 <= words[i].length <= 50
47 | // 1 <= puzzles.length <= 10⁴
48 | // puzzles[i].length == 7
49 | // words[i] and puzzles[i] consist of lowercase English letters.
50 | // Each puzzles[i] does not contain repeated characters.
51 | //
52 | // Related Topics Array Hash Table String Bit Manipulation Trie 👍 676 👎 57
53 |
54 |
55 | package leetcodeProblem.leetcode.editor.en
56 |
57 | class NumberOfValidWordsForEachPuzzle {
58 | fun solution() {
59 | }
60 |
61 | //below code will be used for submission to leetcode (using plugin of course)
62 | //leetcode submit region begin(Prohibit modification and deletion)
63 | class Solution {
64 | fun findNumOfValidWords(words: Array, puzzles: Array): List {
65 | // still find solution
66 | return listOf()
67 | }
68 | }
69 | //leetcode submit region end(Prohibit modification and deletion)
70 |
71 | }
72 |
73 | fun main() {}
74 |
75 |
76 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/PascalsTriangle.kt:
--------------------------------------------------------------------------------
1 | //Given an integer numRows, return the first numRows of Pascal's triangle.
2 | //
3 | // In Pascal's triangle, each number is the sum of the two numbers directly
4 | //above it as shown:
5 | //
6 | //
7 | // Example 1:
8 | // Input: numRows = 5
9 | //Output: [[1],[1,1],[1,2,1],[1,3,3,1],[1,4,6,4,1]]
10 | // Example 2:
11 | // Input: numRows = 1
12 | //Output: [[1]]
13 | //
14 | //
15 | // Constraints:
16 | //
17 | //
18 | // 1 <= numRows <= 30
19 | //
20 | // Related Topics Array Dynamic Programming 👍 3891 👎 170
21 |
22 |
23 | package leetcodeProblem.leetcode.editor.en
24 |
25 | class PascalsTriangle {
26 | fun solution() {
27 | }
28 |
29 | //below code will be used for submission to leetcode (using plugin of course)
30 | //leetcode submit region begin(Prohibit modification and deletion)
31 | class Solution {
32 | fun generate(numRows: Int): List> {
33 | val result = mutableListOf>()
34 | result.add(mutableListOf(1))
35 | if (numRows == 1) return result.toList()
36 | result.add(mutableListOf(1, 1))
37 | if (numRows == 2) return result.toList()
38 |
39 |
40 | for (i in 2 until numRows) {
41 | val temp = mutableListOf()
42 | for (j in 0..i) {
43 | when (j) {
44 | 0 -> temp.add(1)
45 | i -> temp.add(1)
46 | else -> temp.add(result[i - 1][j] + result[i - 1][j - 1])
47 | }
48 | }
49 | result.add(temp)
50 | }
51 | return result.toList()
52 | }
53 | }
54 | //leetcode submit region end(Prohibit modification and deletion)
55 |
56 | }
57 |
58 | fun main() {
59 | val result = PascalsTriangle.Solution().generate(5)
60 | result.forEach {
61 | println(it)
62 | }
63 | }
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/RansomNote.kt:
--------------------------------------------------------------------------------
1 | //Given two stings ransomNote and magazine, return true if ransomNote can be
2 | //constructed from magazine and false otherwise.
3 | //
4 | // Each letter in magazine can only be used once in ransomNote.
5 | //
6 | //
7 | // Example 1:
8 | // Input: ransomNote = "a", magazine = "b"
9 | //Output: false
10 | // Example 2:
11 | // Input: ransomNote = "aa", magazine = "ab"
12 | //Output: false
13 | // Example 3:
14 | // Input: ransomNote = "aa", magazine = "aab"
15 | //Output: true
16 | //
17 | //
18 | // Constraints:
19 | //
20 | //
21 | // 1 <= ransomNote.length, magazine.length <= 10⁵
22 | // ransomNote and magazine consist of lowercase English letters.
23 | //
24 | // Related Topics Hash Table String Counting 👍 1215 👎 266
25 |
26 |
27 | package leetcodeProblem.leetcode.editor.en
28 |
29 | class RansomNote {
30 | fun solution() {
31 | }
32 |
33 | //below code will be used for submission to leetcode (using plugin of course)
34 | //leetcode submit region begin(Prohibit modification and deletion)
35 | class Solution {
36 | fun canConstruct(ransomNote: String, magazine: String): Boolean {
37 | if (ransomNote == magazine) return true
38 | val hashMap = mutableMapOf()
39 | for (i in magazine.indices) {
40 | hashMap[magazine[i]] = hashMap.getOrDefault(magazine[i], 0) + 1
41 | }
42 | for (i in ransomNote.indices) {
43 | if (hashMap.containsKey(ransomNote[i])) {
44 | hashMap[ransomNote[i]] = hashMap[ransomNote[i]]!! - 1
45 | if (hashMap[ransomNote[i]] == 0) hashMap.remove(ransomNote[i])
46 | } else {
47 | return false
48 | }
49 | }
50 | return true
51 | }
52 | }
53 | //leetcode submit region end(Prohibit modification and deletion)
54 |
55 | }
56 |
57 | fun main() {}
58 |
59 |
60 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/RemoveDuplicatesFromSortedListIi.kt:
--------------------------------------------------------------------------------
1 | //Given the head of a sorted linked list, delete all nodes that have duplicate
2 | //numbers, leaving only distinct numbers from the original list. Return the linked
3 | //list sorted as well.
4 | //
5 | //
6 | // Example 1:
7 | //
8 | //
9 | //Input: head = [1,2,3,3,4,4,5]
10 | //Output: [1,2,5]
11 | //
12 | //
13 | // Example 2:
14 | //
15 | //
16 | //Input: head = [1,1,1,2,3]
17 | //Output: [2,3]
18 | //
19 | //
20 | //
21 | // Constraints:
22 | //
23 | //
24 | // The number of nodes in the list is in the range [0, 300].
25 | // -100 <= Node.val <= 100
26 | // The list is guaranteed to be sorted in ascending order.
27 | //
28 | // Related Topics Linked List Two Pointers 👍 3700 👎 134
29 |
30 |
31 | package leetcodeProblem.leetcode.editor.en
32 |
33 | import leetcode_study_badge.data_structure.ListNode
34 |
35 | class RemoveDuplicatesFromSortedListIi {
36 | fun solution() {
37 | }
38 | //below code is used to auto submit for leetcode.com (using ide plugin)
39 | //leetcode submit region begin(Prohibit modification and deletion)
40 | /**
41 | * Example:
42 | * var li = ListNode(5)
43 | * var v = li.`val`
44 | * Definition for singly-linked list.
45 | * class ListNode(var `val`: Int) {
46 | * var next: ListNode? = null
47 | * }
48 | */
49 | class Solution {
50 | // sentinel Algorithm
51 | fun deleteDuplicates(head: ListNode?): ListNode? {
52 | val sentinel = ListNode(0, head)
53 | var preD: ListNode? = sentinel
54 | var head = head
55 | while (head != null) {
56 | if (head.next != null && head.`val` == head.next?.`val`) {
57 | while (head?.next != null && head?.`val` == head?.next?.`val`) {
58 | head = head?.next
59 | }
60 | preD?.next = head?.next
61 | } else {
62 | preD = preD?.next
63 | }
64 | head = head?.next
65 | }
66 | return sentinel.next
67 | }
68 | }
69 | //leetcode submit region end(Prohibit modification and deletion)
70 |
71 | }
72 |
73 | fun main() {}
74 |
75 |
76 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/RemoveLinkedListElements.kt:
--------------------------------------------------------------------------------
1 | //Given the head of a linked list and an integer val, remove all the nodes of
2 | //the linked list that has Node.val == val, and return the new head.
3 | //
4 | //
5 | // Example 1:
6 | //
7 | //
8 | //Input: head = [1,2,6,3,4,5,6], val = 6
9 | //Output: [1,2,3,4,5]
10 | //
11 | //
12 | // Example 2:
13 | //
14 | //
15 | //Input: head = [], val = 1
16 | //Output: []
17 | //
18 | //
19 | // Example 3:
20 | //
21 | //
22 | //Input: head = [7,7,7,7], val = 7
23 | //Output: []
24 | //
25 | //
26 | //
27 | // Constraints:
28 | //
29 | //
30 | // The number of nodes in the list is in the range [0, 10⁴].
31 | // 1 <= Node.val <= 50
32 | // 0 <= val <= 50
33 | //
34 | // Related Topics Linked List Recursion 👍 3859 👎 140
35 |
36 |
37 | package leetcodeProblem.leetcode.editor.en
38 |
39 | class RemoveLinkedListElements {
40 | fun solution() {
41 | }
42 | //below code will be used for submission to leetcode (using plugin of course)
43 | //leetcode submit region begin(Prohibit modification and deletion)
44 | /**
45 | * Example:
46 | * var li = ListNode(5)
47 | * var v = li.`val`
48 | * Definition for singly-linked list.
49 | * class ListNode(var `val`: Int) {
50 | * var next: ListNode? = null
51 | * }
52 | */
53 | class Solution {
54 | fun removeElements(head: ListNode?, `val`: Int): ListNode? {
55 | var current = head
56 | var result = head
57 | var next = ListNode(0)
58 | next.next = result
59 |
60 | while (current != null) {
61 | if (current.`val` == 6) {
62 | result?.next = result?.next?.next
63 | }
64 | result = result?.next
65 | current = current.next
66 | }
67 | return next.next
68 | }
69 | }
70 |
71 | class ListNode(var `val`: Int) {
72 | var next: ListNode? = null
73 | }
74 | //leetcode submit region end(Prohibit modification and deletion)
75 |
76 | }
77 |
78 | fun main() {}
79 |
80 |
81 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/RemoveNthNodeFromEndOfList.kt:
--------------------------------------------------------------------------------
1 | //Given the head of a linked list, remove the nᵗʰ node from the end of the list
2 | //and return its head.
3 | //
4 | //
5 | // Example 1:
6 | //
7 | //
8 | //Input: head = [1,2,3,4,5], n = 2
9 | //Output: [1,2,3,5]
10 | //
11 | //
12 | // Example 2:
13 | //
14 | //
15 | //Input: head = [1], n = 1
16 | //Output: []
17 | //
18 | //
19 | // Example 3:
20 | //
21 | //
22 | //Input: head = [1,2], n = 1
23 | //Output: [1]
24 | //
25 | //
26 | //
27 | // Constraints:
28 | //
29 | //
30 | // The number of nodes in the list is sz.
31 | // 1 <= sz <= 30
32 | // 0 <= Node.val <= 100
33 | // 1 <= n <= sz
34 | //
35 | //
36 | //
37 | // Follow up: Could you do this in one pass?
38 | // Related Topics Linked List Two Pointers 👍 7132 👎 367
39 |
40 |
41 | package leetcodeProblem.leetcode.editor.en
42 |
43 | import leetcode_study_badge.data_structure.ListNode
44 |
45 | class RemoveNthNodeFromEndOfList {
46 | fun solution() {
47 | }
48 | //below code will be used for submission to leetcode (using plugin of course)
49 | //leetcode submit region begin(Prohibit modification and deletion)
50 | /**
51 | * Example:
52 | * var li = ListNode(5)
53 | * var v = li.`val`
54 | * Definition for singly-linked list.
55 | * class ListNode(var `val`: Int) {
56 | * var next: ListNode? = null
57 | * }
58 | */
59 | class Solution {
60 | fun removeNthFromEnd(head: ListNode?, n: Int): ListNode? {
61 | var result = head
62 | var tempResult = result
63 | var current = head
64 | var size = 1
65 | while (current?.next != null) {
66 | size++
67 | current = current?.next
68 | }
69 |
70 | size -= n
71 | if (size == 0) {
72 | tempResult = tempResult?.next
73 | } else {
74 | for (i in 1..size) {
75 | if (i == size) {
76 | result?.next = result?.next?.next
77 | } else {
78 | result = result?.next
79 | }
80 | }
81 | }
82 | return tempResult
83 | }
84 | }
85 | //leetcode submit region end(Prohibit modification and deletion)
86 |
87 | }
88 |
89 | fun main() {}
90 |
91 |
92 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/ReorderList.kt:
--------------------------------------------------------------------------------
1 | //You are given the head of a singly linked-list. The list can be represented
2 | //as:
3 | //
4 | //
5 | //L0 → L1 → … → Ln - 1 → Ln
6 | //
7 | //
8 | // Reorder the list to be on the following form:
9 | //
10 | //
11 | //L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
12 | //
13 | //
14 | // You may not modify the values in the list's nodes. Only nodes themselves may
15 | //be changed.
16 | //
17 | //
18 | // Example 1:
19 | //
20 | //
21 | //Input: head = [1,2,3,4]
22 | //Output: [1,4,2,3]
23 | //
24 | //
25 | // Example 2:
26 | //
27 | //
28 | //Input: head = [1,2,3,4,5]
29 | //Output: [1,5,2,4,3]
30 | //
31 | //
32 | //
33 | // Constraints:
34 | //
35 | //
36 | // The number of nodes in the list is in the range [1, 5 * 10⁴].
37 | // 1 <= Node.val <= 1000
38 | //
39 | // Related Topics Linked List Two Pointers Stack Recursion 👍 4025 👎 170
40 |
41 |
42 | package leetcodeProblem.leetcode.editor.en
43 |
44 | import leetcode_study_badge.data_structure.ListNode
45 |
46 | class ReorderList {
47 | fun solution() {
48 | }
49 | //below code will be used for submission to leetcode (using plugin of course)
50 | //leetcode submit region begin(Prohibit modification and deletion)
51 | /**
52 | * Example:
53 | * var li = ListNode(5)
54 | * var v = li.`val`
55 | * Definition for singly-linked list.
56 | * class ListNode(var `val`: Int) {
57 | * var next: ListNode? = null
58 | * }
59 | */
60 | class Solution {
61 | tailrec fun midPoint(slow: ListNode?, fast: ListNode? = slow): ListNode? =
62 | if (fast?.next == null) slow else midPoint(slow?.next, fast.next?.next)
63 |
64 | tailrec fun reverse(node: ListNode?, reversed: ListNode? = null): ListNode? =
65 | if (node == null) reversed else reverse(node.next.also { node.next = reversed }, node)
66 |
67 | tailrec fun merge(left: ListNode?, right: ListNode?) {
68 | if(left != right) {
69 | val nextRight = right?.next.also { right?.next = left?.next }
70 | val nextLeft = left?.next.also { left?.next = right }
71 | if (right != null) merge(nextLeft, nextRight)
72 | }
73 | }
74 | fun reorderList(head: ListNode?) = merge(head, reverse(midPoint(head)))
75 | }
76 | //leetcode submit region end(Prohibit modification and deletion)
77 |
78 | }
79 |
80 | fun main() {}
81 |
82 |
83 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/ReshapeTheMatrix.kt:
--------------------------------------------------------------------------------
1 | //In MATLAB, there is a handy function called reshape which can reshape an m x
2 | //n matrix into a new one with a different size r x c keeping its original data.
3 | //
4 | // You are given an m x n matrix mat and two integers r and c representing the
5 | //number of rows and the number of columns of the wanted reshaped matrix.
6 | //
7 | // The reshaped matrix should be filled with all the elements of the original
8 | //matrix in the same row-traversing order as they were.
9 | //
10 | // If the reshape operation with given parameters is possible and legal, output
11 | //the new reshaped matrix; Otherwise, output the original matrix.
12 | //
13 | //
14 | // Example 1:
15 | //
16 | //
17 | //Input: mat = [[1,2],[3,4]], r = 1, c = 4
18 | //Output: [[1,2,3,4]]
19 | //
20 | //
21 | // Example 2:
22 | //
23 | //
24 | //Input: mat = [[1,2],[3,4]], r = 2, c = 4
25 | //Output: [[1,2],[3,4]]
26 | //
27 | //
28 | //
29 | // Constraints:
30 | //
31 | //
32 | // m == mat.length
33 | // n == mat[i].length
34 | // 1 <= m, n <= 100
35 | // -1000 <= mat[i][j] <= 1000
36 | // 1 <= r, c <= 300
37 | //
38 | // Related Topics Array Matrix Simulation 👍 1527 👎 168
39 |
40 |
41 | package leetcodeProblem.leetcode.editor.en
42 |
43 | class ReshapeTheMatrix {
44 | fun solution() {
45 | }
46 |
47 | //below code will be used for submission to leetcode (using plugin of course)
48 | //leetcode submit region begin(Prohibit modification and deletion)
49 | class Solution {
50 | fun matrixReshape(nums: Array, r: Int, c: Int): Array {
51 |
52 | val mutableList = mutableListOf()
53 |
54 | nums.forEach { intArray ->
55 |
56 | intArray.forEach { int ->
57 |
58 | mutableList.add(int)
59 | }
60 | }
61 |
62 | if (mutableList.count() != r * c) return nums
63 |
64 | val answer = Array(r) { IntArray(c) }
65 |
66 | var index = 0
67 |
68 | for (row in 0 until r) {
69 |
70 | for (column in 0 until c) {
71 |
72 | answer[row][column] = mutableList[index]
73 |
74 | index++
75 | }
76 | }
77 |
78 | return answer
79 | }
80 | }
81 | //leetcode submit region end(Prohibit modification and deletion)
82 |
83 | }
84 |
85 | fun main() {}
86 |
87 |
88 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/ReverseLinkedList.kt:
--------------------------------------------------------------------------------
1 | //Given the head of a singly linked list, reverse the list, and return the
2 | //reversed list.
3 | //
4 | //
5 | // Example 1:
6 | //
7 | //
8 | //Input: head = [1,2,3,4,5]
9 | //Output: [5,4,3,2,1]
10 | //
11 | //
12 | // Example 2:
13 | //
14 | //
15 | //Input: head = [1,2]
16 | //Output: [2,1]
17 | //
18 | //
19 | // Example 3:
20 | //
21 | //
22 | //Input: head = []
23 | //Output: []
24 | //
25 | //
26 | //
27 | // Constraints:
28 | //
29 | //
30 | // The number of nodes in the list is the range [0, 5000].
31 | // -5000 <= Node.val <= 5000
32 | //
33 | //
34 | //
35 | // Follow up: A linked list can be reversed either iteratively or recursively.
36 | //Could you implement both?
37 | // Related Topics Linked List Recursion 👍 8776 👎 153
38 |
39 |
40 | package leetcodeProblem.leetcode.editor.en
41 |
42 | import leetcode_study_badge.data_structure.ListNode
43 |
44 | class ReverseLinkedList {
45 | fun solution() {
46 | }
47 | //below code is used to auto submit to leetcode.com (using ide plugin)
48 | //leetcode submit region begin(Prohibit modification and deletion)
49 | /**
50 | * Example:
51 | * var li = ListNode(5)
52 | * var v = li.`val`
53 | * Definition for singly-linked list.
54 | * class ListNode(var `val`: Int) {
55 | * var next: ListNode? = null
56 | * }
57 | */
58 | class Solution {
59 | fun reverseList(head: ListNode?): ListNode? {
60 | if (head == null) return head
61 | return recurReverseList(head, null)
62 | }
63 |
64 | private fun recurReverseList(p: ListNode?, l: ListNode?): ListNode? {
65 | if (p == null) return l
66 |
67 | val n = p.next
68 | p.next = l
69 |
70 | return recurReverseList(n, p)
71 | }
72 |
73 | }
74 | //leetcode submit region end(Prohibit modification and deletion)
75 |
76 | }
77 |
78 | fun main() {}
79 |
80 |
81 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/ReverseString.kt:
--------------------------------------------------------------------------------
1 | //Write a function that reverses a string. The input string is given as an
2 | //array of characters s.
3 | //
4 | //
5 | // Example 1:
6 | // Input: s = ["h","e","l","l","o"]
7 | //Output: ["o","l","l","e","h"]
8 | // Example 2:
9 | // Input: s = ["H","a","n","n","a","h"]
10 | //Output: ["h","a","n","n","a","H"]
11 | //
12 | //
13 | // Constraints:
14 | //
15 | //
16 | // 1 <= s.length <= 10⁵
17 | // s[i] is a printable ascii character.
18 | //
19 | //
20 | //
21 | // Follow up: Do not allocate extra space for another array. You must do this
22 | //by modifying the input array in-place with O(1) extra memory.
23 | // Related Topics Two Pointers String Recursion 👍 3178 👎 839
24 |
25 |
26 | package leetcodeProblem.leetcode.editor.en
27 |
28 | class ReverseString {
29 | fun solution() {
30 | }
31 |
32 | //below code will be used for submission to leetcode (using plugin of course)
33 | //leetcode submit region begin(Prohibit modification and deletion)
34 | class Solution {
35 | fun reverseString(s: CharArray): Unit {
36 | var left = 0
37 | var right = s.size - 1
38 | while (left < right) {
39 | val temp = s[left]
40 | s[left] = s[right]
41 | s[right] = temp
42 | left++
43 | right--
44 | }
45 | }
46 | }
47 | //leetcode submit region end(Prohibit modification and deletion)
48 |
49 | }
50 |
51 | fun main() {}
52 |
53 |
54 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/ReverseWordsInAStringIii.kt:
--------------------------------------------------------------------------------
1 | //Given a string s, reverse the order of characters in each word within a
2 | //sentence while still preserving whitespace and initial word order.
3 | //
4 | //
5 | // Example 1:
6 | // Input: s = "Let's take LeetCode contest"
7 | //Output: "s'teL ekat edoCteeL tsetnoc"
8 | // Example 2:
9 | // Input: s = "God Ding"
10 | //Output: "doG gniD"
11 | //
12 | //
13 | // Constraints:
14 | //
15 | //
16 | // 1 <= s.length <= 5 * 10⁴
17 | // s contains printable ASCII characters.
18 | // s does not contain any leading or trailing spaces.
19 | // There is at least one word in s.
20 | // All the words in s are separated by a single space.
21 | //
22 | // Related Topics Two Pointers String 👍 1910 👎 121
23 |
24 |
25 | package leetcodeProblem.leetcode.editor.en
26 |
27 | class ReverseWordsInAStringIii {
28 | fun solution() {
29 | }
30 |
31 | //below code will be used for submission to leetcode (using plugin of course)
32 | //leetcode submit region begin(Prohibit modification and deletion)
33 | class Solution {
34 | fun reverseWords(s: String): String {
35 | var s = s.toCharArray()
36 | var left = 0
37 | var right = 1
38 | while (right < s.size) {
39 |
40 | if (s[right].isWhitespace() && !s[right - 1].isWhitespace() && right > 1 || right == s.lastIndex && right > 1) {
41 | var tempLeft = left
42 | var tempRight = right - 1
43 | while (tempLeft < tempRight) {
44 | val temp = s[tempRight]
45 | s[tempRight] = s[tempLeft]
46 | s[tempLeft] = temp
47 | tempLeft++
48 | tempRight--
49 | }
50 | left = right + 1
51 | right++
52 | } else if (s[right].isWhitespace() && s[right - 1].isWhitespace()) {
53 | left = right + 1
54 | right++
55 | } else {
56 | right++
57 | }
58 | }
59 | return String(s)
60 | }
61 | }
62 | //leetcode submit region end(Prohibit modification and deletion)
63 |
64 | }
65 |
66 | fun main() {
67 | ReverseWordsInAStringIii.Solution().reverseWords("Let's take LeetCode contest")
68 | }
69 |
70 |
71 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/RotateArray.kt:
--------------------------------------------------------------------------------
1 | //Given an array, rotate the array to the right by k steps, where k is non-
2 | //negative.
3 | //
4 | //
5 | // Example 1:
6 | //
7 | //
8 | //Input: nums = [1,2,3,4,5,6,7], k = 3
9 | //Output: [5,6,7,1,2,3,4]
10 | //Explanation:
11 | //rotate 1 steps to the right: [7,1,2,3,4,5,6]
12 | //rotate 2 steps to the right: [6,7,1,2,3,4,5]
13 | //rotate 3 steps to the right: [5,6,7,1,2,3,4]
14 | //
15 | //
16 | // Example 2:
17 | //
18 | //
19 | //Input: nums = [-1,-100,3,99], k = 2
20 | //Output: [3,99,-1,-100]
21 | //Explanation:
22 | //rotate 1 steps to the right: [99,-1,-100,3]
23 | //rotate 2 steps to the right: [3,99,-1,-100]
24 | //
25 | //
26 | //
27 | // Constraints:
28 | //
29 | //
30 | // 1 <= nums.length <= 10⁵
31 | // -2³¹ <= nums[i] <= 2³¹ - 1
32 | // 0 <= k <= 10⁵
33 | //
34 | //
35 | //
36 | // Follow up:
37 | //
38 | //
39 | // Try to come up with as many solutions as you can. There are at least three
40 | //different ways to solve this problem.
41 | // Could you do it in-place with O(1) extra space?
42 | //
43 | // Related Topics Array Math Two Pointers 👍 6302 👎 1055
44 |
45 |
46 | package leetcodeProblem.leetcode.editor.en
47 |
48 | class RotateArray {
49 | fun solution() {
50 | }
51 |
52 | //below code will be used for submission to leetcode (using plugin of course)
53 | //leetcode submit region begin(Prohibit modification and deletion)
54 | class Solution {
55 |
56 | fun rotate(nums: IntArray, k: Int) {
57 | var k = k
58 | k %= nums.size
59 | reverse(nums, 0, nums.size - 1)
60 | reverse(nums, 0, k - 1)
61 | reverse(nums, k, nums.size - 1)
62 | }
63 |
64 | private fun reverse(nums: IntArray, start: Int, end: Int) {
65 | var start = start
66 | var end = end
67 | while (start < end) {
68 | val temp = nums[start]
69 | nums[start] = nums[end]
70 | nums[end] = temp
71 | start++
72 | end--
73 | }
74 | }
75 | }
76 | //leetcode submit region end(Prohibit modification and deletion)
77 |
78 | }
79 |
80 | fun main() {
81 | println(RotateArray.Solution().rotate(intArrayOf(1, 2, 3, 4, 5, 6 , 7) , 3))
82 | }
83 |
84 |
85 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/SearchA2dMatrix.kt:
--------------------------------------------------------------------------------
1 | //Write an efficient algorithm that searches for a value in an m x n matrix.
2 | //This matrix has the following properties:
3 | //
4 | //
5 | // Integers in each row are sorted from left to right.
6 | // The first integer of each row is greater than the last integer of the
7 | //previous row.
8 | //
9 | //
10 | //
11 | // Example 1:
12 | //
13 | //
14 | //Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
15 | //Output: true
16 | //
17 | //
18 | // Example 2:
19 | //
20 | //
21 | //Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 13
22 | //Output: false
23 | //
24 | //
25 | //
26 | // Constraints:
27 | //
28 | //
29 | // m == matrix.length
30 | // n == matrix[i].length
31 | // 1 <= m, n <= 100
32 | // -10⁴ <= matrix[i][j], target <= 10⁴
33 | //
34 | // Related Topics Array Binary Search Matrix 👍 4843 👎 223
35 |
36 |
37 | package leetcodeProblem.leetcode.editor.en
38 |
39 | class SearchA2dMatrix {
40 | fun solution() {
41 | }
42 |
43 | //below code will be used for submission to leetcode (using plugin of course)
44 | //leetcode submit region begin(Prohibit modification and deletion)
45 | class Solution {
46 | fun searchMatrix(matrix: Array, target: Int): Boolean {
47 | for (i in matrix.indices) {
48 | if (matrix[i][matrix.size - 1] == target) {
49 | return true
50 | }
51 | if (matrix[i][matrix.size] > target) {
52 | var rightSearch = matrix[i].size - 1
53 | var leftSearch = 0
54 | while (leftSearch <= rightSearch) {
55 | val middleSearch = leftSearch + (rightSearch - leftSearch) / 2
56 | val valueNow = matrix[i][middleSearch]
57 | if (valueNow == target) {
58 | return true
59 | } else if (valueNow > target) {
60 | rightSearch = middleSearch - 1
61 | } else {
62 | leftSearch = middleSearch + 1
63 | }
64 | }
65 | break
66 | }
67 | }
68 |
69 | return false
70 | }
71 | }
72 | //leetcode submit region end(Prohibit modification and deletion)
73 |
74 | }
75 |
76 | fun main() {}
77 |
78 |
79 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/SearchInRotatedSortedArray.kt:
--------------------------------------------------------------------------------
1 | //There is an integer array nums sorted in ascending order (with distinct
2 | //values).
3 | //
4 | // Prior to being passed to your function, nums is possibly rotated at an
5 | //unknown pivot index k (1 <= k < nums.length) such that the resulting array is [nums[k]
6 | //, nums[k+1], ..., nums[n-1], nums[0], nums[1], ..., nums[k-1]] (0-indexed). For
7 | //example, [0,1,2,4,5,6,7] might be rotated at pivot index 3 and become [4,5,6,7,0
8 | //,1,2].
9 | //
10 | // Given the array nums after the possible rotation and an integer target,
11 | //return the index of target if it is in nums, or -1 if it is not in nums.
12 | //
13 | // You must write an algorithm with O(log n) runtime complexity.
14 | //
15 | //
16 | // Example 1:
17 | // Input: nums = [4,5,6,7,0,1,2], target = 0
18 | //Output: 4
19 | // Example 2:
20 | // Input: nums = [4,5,6,7,0,1,2], target = 3
21 | //Output: -1
22 | // Example 3:
23 | // Input: nums = [1], target = 0
24 | //Output: -1
25 | //
26 | //
27 | // Constraints:
28 | //
29 | //
30 | // 1 <= nums.length <= 5000
31 | // -10⁴ <= nums[i] <= 10⁴
32 | // All values of nums are unique.
33 | // nums is an ascending array that is possibly rotated.
34 | // -10⁴ <= target <= 10⁴
35 | //
36 | // Related Topics Array Binary Search 👍 10540 👎 772
37 |
38 |
39 | package leetcodeProblem.leetcode.editor.en
40 |
41 | class SearchInRotatedSortedArray {
42 | fun solution() {
43 | }
44 |
45 | //below code will be used for submission to leetcode (using plugin of course)
46 | //leetcode submit region begin(Prohibit modification and deletion)
47 | class Solution {
48 | fun search(nums: IntArray, target: Int): Int {
49 | var l = 0
50 | var r = nums.size - 1
51 | // t =4
52 |
53 | while (l <= r) {
54 | val m = l + (r - l) / 2 //
55 | if (nums[m] == target) {
56 | return m
57 | }
58 |
59 | if (nums[l] <= nums[m]) {
60 | if (target > nums[m] || target < nums[l]) l = m + 1 else r = m - 1
61 | } else {
62 | if (target < nums[m] || target > nums[r]) r = m - 1 else l = m + 1
63 | }
64 | }
65 |
66 | return -1
67 | }
68 | }
69 | //leetcode submit region end(Prohibit modification and deletion)
70 |
71 | }
72 |
73 | fun main() {
74 | SearchInRotatedSortedArray.Solution().search(intArrayOf(4,5,6,7,0,1,2) , 4)
75 | }
76 |
77 |
78 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/SetMatrixZeroes.kt:
--------------------------------------------------------------------------------
1 | //Given an m x n integer matrix matrix, if an element is 0, set its entire row
2 | //and column to 0's, and return the matrix.
3 | //
4 | // You must do it in place.
5 | //
6 | //
7 | // Example 1:
8 | //
9 | //
10 | //Input: matrix = [[1,1,1],[1,0,1],[1,1,1]]
11 | //Output: [[1,0,1],[0,0,0],[1,0,1]]
12 | //
13 | //
14 | // Example 2:
15 | //
16 | //
17 | //Input: matrix = [[0,1,2,0],[3,4,5,2],[1,3,1,5]]
18 | //Output: [[0,0,0,0],[0,4,5,0],[0,3,1,0]]
19 | //
20 | //
21 | //
22 | // Constraints:
23 | //
24 | //
25 | // m == matrix.length
26 | // n == matrix[0].length
27 | // 1 <= m, n <= 200
28 | // -2³¹ <= matrix[i][j] <= 2³¹ - 1
29 | //
30 | //
31 | //
32 | // Follow up:
33 | //
34 | //
35 | // A straightforward solution using O(mn) space is probably a bad idea.
36 | // A simple improvement uses O(m + n) space, but still not the best solution.
37 | // Could you devise a constant space solution?
38 | //
39 | // Related Topics Array Hash Table Matrix 👍 5009 👎 434
40 |
41 |
42 | package leetcodeProblem.leetcode.editor.en
43 |
44 |
45 | class SetMatrixZeroes {
46 | fun solution() {
47 | }
48 |
49 | //below code will be used for submission to leetcode (using plugin of course)
50 | //leetcode submit region begin(Prohibit modification and deletion)
51 | internal class Solution {
52 | fun setZeroes(matrix: Array) {
53 | val R = matrix.size
54 | val C: Int = matrix[0].size
55 | val rows: MutableSet = HashSet()
56 | val cols: MutableSet = HashSet()
57 |
58 |
59 | for (i in 0 until R) {
60 | for (j in 0 until C) {
61 | if (matrix[i][j] == 0) {
62 | rows.add(i)
63 | cols.add(j)
64 | }
65 | }
66 | }
67 |
68 |
69 | for (i in 0 until R) {
70 | for (j in 0 until C) {
71 | if (rows.contains(i) || cols.contains(j)) {
72 | matrix[i][j] = 0
73 | }
74 | }
75 | }
76 | }
77 | }
78 | //leetcode submit region end(Prohibit modification and deletion)
79 |
80 | }
81 |
82 | fun main() {}
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
97 |
98 |
99 |
100 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/SingleNumberIii.kt:
--------------------------------------------------------------------------------
1 | //Given an integer array nums, in which exactly two elements appear only once
2 | //and all the other elements appear exactly twice. Find the two elements that
3 | //appear only once. You can return the answer in any order.
4 | //
5 | // You must write an algorithm that runs in linear runtime complexity and uses
6 | //only constant extra space.
7 | //
8 | //
9 | // Example 1:
10 | //
11 | //
12 | //Input: nums = [1,2,1,3,2,5]
13 | //Output: [3,5]
14 | //Explanation: [5, 3] is also a valid answer.
15 | //
16 | //
17 | // Example 2:
18 | //
19 | //
20 | //Input: nums = [-1,0]
21 | //Output: [-1,0]
22 | //
23 | //
24 | // Example 3:
25 | //
26 | //
27 | //Input: nums = [0,1]
28 | //Output: [1,0]
29 | //
30 | //
31 | //
32 | // Constraints:
33 | //
34 | //
35 | // 2 <= nums.length <= 3 * 10⁴
36 | // -2³¹ <= nums[i] <= 2³¹ - 1
37 | // Each integer in nums will appear twice, only two integers will appear once.
38 | //
39 | // Related Topics Array Bit Manipulation 👍 3157 👎 167
40 |
41 |
42 | package leetcodeProblem.leetcode.editor.en
43 |
44 | class SingleNumberIii {
45 | fun solution() {
46 | }
47 |
48 | //below code will be used for submission to leetcode (using plugin of course)
49 | //leetcode submit region begin(Prohibit modification and deletion)
50 | class Solution {
51 | fun singleNumber(nums: IntArray): IntArray {
52 |
53 | var aXORb = 0
54 | for (n in nums) {
55 | aXORb = aXORb.xor(n)
56 | }
57 |
58 | val rightSetBit = aXORb and -aXORb
59 | var a = 0
60 | for (n in nums) {
61 | if (n and rightSetBit != 0) {
62 | a = a.xor(n)
63 | }
64 | }
65 |
66 | return intArrayOf(a, aXORb xor a)
67 | }
68 | }
69 | //leetcode submit region end(Prohibit modification and deletion)
70 |
71 | }
72 |
73 | fun main() {}
74 |
75 |
76 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/StringWithoutAaaOrBbb.kt:
--------------------------------------------------------------------------------
1 | //Given two integers a and b, return any string s such that:
2 | //
3 | //
4 | // s has length a + b and contains exactly a 'a' letters, and exactly b 'b'
5 | //letters,
6 | // The substring 'aaa' does not occur in s, and
7 | // The substring 'bbb' does not occur in s.
8 | //
9 | //
10 | //
11 | // Example 1:
12 | //
13 | //
14 | //Input: a = 1, b = 2
15 | //Output: "abb"
16 | //Explanation: "abb", "bab" and "bba" are all correct answers.
17 | //
18 | //
19 | // Example 2:
20 | //
21 | //
22 | //Input: a = 4, b = 1
23 | //Output: "aabaa"
24 | //
25 | //
26 | //
27 | // Constraints:
28 | //
29 | //
30 | // 0 <= a, b <= 100
31 | // It is guaranteed such an s exists for the given a and b.
32 | //
33 | // Related Topics String Greedy 👍 392 👎 307
34 |
35 |
36 | package leetcodeProblem.leetcode.editor.en
37 |
38 | class StringWithoutAaaOrBbb {
39 | fun solution() {
40 | }
41 |
42 | //below code will be used for submission to leetcode (using plugin of course)
43 | //leetcode submit region begin(Prohibit modification and deletion)
44 | class Solution {
45 | fun strWithout3a3b(A: Int, B: Int): String {
46 | var A = A
47 | var B = B
48 | val ans = StringBuilder()
49 | while (A > 0 || B > 0) {
50 | var writeA = false
51 | val L = ans.length
52 | if (L >= 2 && ans[L - 1] == ans[L - 2]) {
53 | if (ans[L - 1] == 'b') writeA = true
54 | } else {
55 | if (A >= B) writeA = true
56 | }
57 | if (writeA) {
58 | A--
59 | ans.append('a')
60 | } else {
61 | B--
62 | ans.append('b')
63 | }
64 | }
65 | return ans.toString()
66 | }
67 | }
68 | //leetcode submit region end(Prohibit modification and deletion)
69 |
70 | }
71 |
72 | fun main() {}
73 |
74 |
75 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/SubtreeOfAnotherTree.kt:
--------------------------------------------------------------------------------
1 | //Given the roots of two binary trees root and subRoot, return true if there is
2 | //a subtree of root with the same structure and node values of subRoot and false
3 | //otherwise.
4 | //
5 | // A subtree of a binary tree tree is a tree that consists of a node in tree
6 | //and all of this node's descendants. The tree tree could also be considered as a
7 | //subtree of itself.
8 | //
9 | //
10 | // Example 1:
11 | //
12 | //
13 | //Input: root = [3,4,5,1,2], subRoot = [4,1,2]
14 | //Output: true
15 | //
16 | //
17 | // Example 2:
18 | //
19 | //
20 | //Input: root = [3,4,5,1,2,null,null,null,null,0], subRoot = [4,1,2]
21 | //Output: false
22 | //
23 | //
24 | //
25 | // Constraints:
26 | //
27 | //
28 | // The number of nodes in the root tree is in the range [1, 2000].
29 | // The number of nodes in the subRoot tree is in the range [1, 1000].
30 | // -10⁴ <= root.val <= 10⁴
31 | // -10⁴ <= subRoot.val <= 10⁴
32 | //
33 | // Related Topics Tree Depth-First Search String Matching Binary Tree Hash
34 | //Function 👍 4336 👎 205
35 |
36 |
37 | package leetcodeProblem.leetcode.editor.en
38 |
39 | import data_structure.tree.TreeNode
40 |
41 | class SubtreeOfAnotherTree {
42 | fun solution() {
43 | }
44 | //below code will be used for submission to leetcode (using plugin of course)
45 | //leetcode submit region begin(Prohibit modification and deletion)
46 | /**
47 | * Example:
48 | * var ti = TreeNode(5)
49 | * var v = ti.value
50 | * Definition for a binary tree node.
51 | * class TreeNode(var value: Int) {
52 | * var left: TreeNode? = null
53 | * var right: TreeNode? = null
54 | * }
55 | */
56 | /**
57 | * Example:
58 | * var ti = TreeNode(5)
59 | * var v = ti.value
60 | * Definition for a binary tree node.
61 | * class TreeNode(var value: Int) {
62 | * var left: TreeNode? = null
63 | * var right: TreeNode? = null
64 | * }
65 | */
66 | class Solution {
67 | private var result = false
68 | fun isSubtree(root: TreeNode?, subRoot: TreeNode?): Boolean {
69 |
70 | fun check(n1: TreeNode?, n2: TreeNode?): Boolean {
71 | if (n1 == null && n2 == null) return true else if (n1 == null || n2 == null) return false
72 | return if (n1.value == n2.value) check(n1.left, n2.left) && check(n1.right, n2.right) else false
73 | }
74 |
75 | fun dfs(t1: TreeNode?, t2: TreeNode?) {
76 | if (t1 == null) return
77 | dfs(t1.left, t2)
78 | if (t1?.value == t2?.value) {
79 | result = result || check(t1, t2)
80 | if (result) return
81 | }
82 | dfs(t1.right, t2)
83 | }
84 |
85 | dfs(root, subRoot)
86 |
87 | return result
88 | }
89 | }
90 | //leetcode submit region end(Prohibit modification and deletion)
91 |
92 | }
93 |
94 | fun main() {}
95 |
96 |
97 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/SumOfBeautyInTheArray.kt:
--------------------------------------------------------------------------------
1 | //You are given a 0-indexed integer array nums. For each index i (1 <= i <=
2 | //nums.length - 2) the beauty of nums[i] equals:
3 | //
4 | //
5 | // 2, if nums[j] < nums[i] < nums[k], for all 0 <= j < i and for all i < k <=
6 | //nums.length - 1.
7 | // 1, if nums[i - 1] < nums[i] < nums[i + 1], and the previous condition is not
8 | //satisfied.
9 | // 0, if none of the previous conditions holds.
10 | //
11 | //
12 | // Return the sum of beauty of all nums[i] where 1 <= i <= nums.length - 2.
13 | //
14 | //
15 | // Example 1:
16 | //
17 | //
18 | //Input: nums = [1,2,3]
19 | //Output: 2
20 | //Explanation: For each index i in the range 1 <= i <= 1:
21 | //- The beauty of nums[1] equals 2.
22 | //
23 | //
24 | // Example 2:
25 | //
26 | //
27 | //Input: nums = [2,4,6,4]
28 | //Output: 1
29 | //Explanation: For each index i in the range 1 <= i <= 2:
30 | //- The beauty of nums[1] equals 1.
31 | //- The beauty of nums[2] equals 0.
32 | //
33 | //
34 | // Example 3:
35 | //
36 | //
37 | //Input: nums = [3,2,1]
38 | //Output: 0
39 | //Explanation: For each index i in the range 1 <= i <= 1:
40 | //- The beauty of nums[1] equals 0.
41 | //
42 | //
43 | //
44 | // Constraints:
45 | //
46 | //
47 | // 3 <= nums.length <= 10⁵
48 | // 1 <= nums[i] <= 10⁵
49 | //
50 | // Related Topics Array 👍 191 👎 19
51 |
52 |
53 | package leetcodeProblem.leetcode.editor.en
54 |
55 | class SumOfBeautyInTheArray {
56 | fun solution() {
57 | }
58 |
59 | //below code will be used for submission to leetcode (using plugin of course)
60 | //leetcode submit region begin(Prohibit modification and deletion)
61 | class Solution {
62 | fun sumOfBeauties(nums: IntArray): Int {
63 | var sumOfBeauties = 0
64 | for (i in nums.indices) {
65 |
66 | if (nums[i - 1] < nums[i] && nums[i] < nums[i + 1]) {
67 | sumOfBeauties++
68 | }
69 | }
70 |
71 | return 0
72 | }
73 | }
74 | //leetcode submit region end(Prohibit modification and deletion)
75 |
76 | }
77 |
78 | fun main() {}
79 |
80 |
81 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/SwapNodesInPairs.kt:
--------------------------------------------------------------------------------
1 | //Given a linked list, swap every two adjacent nodes and return its head. You
2 | //must solve the problem without modifying the values in the list's nodes (i.e.,
3 | //only nodes themselves may be changed.)
4 | //
5 | //
6 | // Example 1:
7 | //
8 | //
9 | //Input: head = [1,2,3,4]
10 | //Output: [2,1,4,3]
11 | //
12 | //
13 | // Example 2:
14 | //
15 | //
16 | //Input: head = []
17 | //Output: []
18 | //
19 | //
20 | // Example 3:
21 | //
22 | //
23 | //Input: head = [1]
24 | //Output: [1]
25 | //
26 | //
27 | //
28 | // Constraints:
29 | //
30 | //
31 | // The number of nodes in the list is in the range [0, 100].
32 | // 0 <= Node.val <= 100
33 | //
34 | // Related Topics Linked List Recursion 👍 4687 👎 248
35 |
36 |
37 | package leetcodeProblem.leetcode.editor.en
38 |
39 | import leetcode_study_badge.data_structure.ListNode
40 |
41 | class SwapNodesInPairs {
42 | fun solution() {
43 | }
44 | //below code is used to auto submit to leetcode.com (using ide plugin)
45 | //leetcode submit region begin(Prohibit modification and deletion)
46 | /**
47 | * Example:
48 | * var li = ListNode(5)
49 | * var v = li.`val`
50 | * Definition for singly-linked list.
51 | * class ListNode(var `val`: Int) {
52 | * var next: ListNode? = null
53 | * }
54 | */
55 | class Solution {
56 | fun swapPairs(head: ListNode?): ListNode? {
57 | return helpSwap(head, head?.next)
58 | }
59 |
60 | private fun helpSwap(head: ListNode?, next: ListNode?): ListNode? {
61 | if (head == null) return null
62 | if (next == null) return head
63 | val nextPair = next.next
64 | next.next = head
65 | head.next = helpSwap(nextPair, nextPair?.next)
66 | return next
67 | }
68 | }
69 | //leetcode submit region end(Prohibit modification and deletion)
70 |
71 | }
72 |
73 | fun main() {}
74 |
75 |
76 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/ThreeSum.kt:
--------------------------------------------------------------------------------
1 | //Given an integer array nums, return all the triplets [nums[i], nums[j], nums[
2 | //k]] such that i != j, i != k, and j != k, and nums[i] + nums[j] + nums[k] == 0.
3 | //
4 | // Notice that the solution set must not contain duplicate triplets.
5 | //
6 | //
7 | // Example 1:
8 | // Input: nums = [-1,0,1,2,-1,-4]
9 | //Output: [[-1,-1,2],[-1,0,1]]
10 | // Example 2:
11 | // Input: nums = []
12 | //Output: []
13 | // Example 3:
14 | // Input: nums = [0]
15 | //Output: []
16 | //
17 | //
18 | // Constraints:
19 | //
20 | //
21 | // 0 <= nums.length <= 3000
22 | // -10⁵ <= nums[i] <= 10⁵
23 | //
24 | // Related Topics Array Two Pointers Sorting 👍 13427 👎 1296
25 |
26 |
27 | package leetcodeProblem.leetcode.editor.en
28 |
29 | class ThreeSum {
30 | fun solution() {
31 | }
32 |
33 | //below code will be used for submission to leetcode (using plugin of course)
34 | //leetcode submit region begin(Prohibit modification and deletion)
35 | class Solution {
36 | fun threeSum(nums: IntArray): List> {
37 | var res = HashSet>()
38 | nums.sort()
39 | for (i in 0 until nums.lastIndex - 1) {
40 | var j = i + 1
41 | var k = nums.lastIndex
42 | val tmp = -nums[i]
43 | while (j < k) {
44 | val sum = nums[j] + nums[k]
45 | when {
46 | sum == tmp -> {
47 | res.add(listOf(nums[i], nums[j], nums[k]))
48 | j++
49 | k--
50 | }
51 | sum < tmp -> {
52 | j++
53 | }
54 | else -> {
55 | k--
56 | }
57 | }
58 | }
59 | }
60 | return res.toList()
61 | }
62 | }
63 | //leetcode submit region end(Prohibit modification and deletion)
64 |
65 | }
66 |
67 | fun main() {}
68 |
69 |
70 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/TwoSum.kt:
--------------------------------------------------------------------------------
1 | //Given an array of integers nums and an integer target, return indices of the
2 | //two numbers such that they add up to target.
3 | //
4 | // You may assume that each input would have exactly one solution, and you may
5 | //not use the same element twice.
6 | //
7 | // You can return the answer in any order.
8 | //
9 | //
10 | // Example 1:
11 | //
12 | //
13 | //Input: nums = [2,7,11,15], target = 9
14 | //Output: [0,1]
15 | //Output: Because nums[0] + nums[1] == 9, we return [0, 1].
16 | //
17 | //
18 | // Example 2:
19 | //
20 | //
21 | //Input: nums = [3,2,4], target = 6
22 | //Output: [1,2]
23 | //
24 | //
25 | // Example 3:
26 | //
27 | //
28 | //Input: nums = [3,3], target = 6
29 | //Output: [0,1]
30 | //
31 | //
32 | //
33 | // Constraints:
34 | //
35 | //
36 | // 2 <= nums.length <= 10⁴
37 | // -10⁹ <= nums[i] <= 10⁹
38 | // -10⁹ <= target <= 10⁹
39 | // Only one valid answer exists.
40 | //
41 | //
42 | //
43 | //Follow-up: Can you come up with an algorithm that is less than O(n²) time
44 | //complexity? Related Topics Array Hash Table 👍 25239 👎 820
45 |
46 |
47 | package leetcodeProblem.leetcode.editor.en
48 |
49 | class TwoSum {
50 | fun solution() {
51 | }
52 |
53 | //below code is used to auto submit to leetcode.com (using ide plugin)
54 | //leetcode submit region begin(Prohibit modification and deletion)
55 | class Solution {
56 | fun twoSum(nums: IntArray, target: Int): IntArray {
57 | val mutableMap = mutableMapOf()
58 | nums.forEachIndexed { index, it ->
59 | if (mutableMap.containsKey(target - it)) {
60 | return intArrayOf(mutableMap[target - it] ?: 0, index)
61 | } else {
62 | mutableMap[it] = index
63 | }
64 | }
65 | return intArrayOf()
66 | }
67 | }
68 | //leetcode submit region end(Prohibit modification and deletion)
69 |
70 | }
71 |
72 | fun main() {}
73 |
74 |
75 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/TwoSumIiInputArrayIsSorted.kt:
--------------------------------------------------------------------------------
1 | //Given a 1-indexed array of integers numbers that is already sorted in non-
2 | //decreasing order, find two numbers such that they add up to a specific target
3 | //number. Let these two numbers be numbers[index1] and numbers[index2] where 1 <= first
4 | //< second <= numbers.length.
5 | //
6 | // Return the indices of the two numbers, index1 and index2, as an integer
7 | //array [index1, index2] of length 2.
8 | //
9 | // The tests are generated such that there is exactly one solution. You may not
10 | //use the same element twice.
11 | //
12 | //
13 | // Example 1:
14 | //
15 | //
16 | //Input: numbers = [2,7,11,15], target = 9
17 | //Output: [1,2]
18 | //Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
19 | //
20 | //
21 | // Example 2:
22 | //
23 | //
24 | //Input: numbers = [2,3,4], target = 6
25 | //Output: [1,3]
26 | //Explanation: The sum of 2 and 4 is 6. Therefore index1 = 1, index2 = 3.
27 | //
28 | //
29 | // Example 3:
30 | //
31 | //
32 | //Input: numbers = [-1,0], target = -1
33 | //Output: [1,2]
34 | //Explanation: The sum of -1 and 0 is -1. Therefore index1 = 1, index2 = 2.
35 | //
36 | //
37 | //
38 | // Constraints:
39 | //
40 | //
41 | // 2 <= numbers.length <= 3 * 10⁴
42 | // -1000 <= numbers[i] <= 1000
43 | // numbers is sorted in non-decreasing order.
44 | // -1000 <= target <= 1000
45 | // The tests are generated such that there is exactly one solution.
46 | //
47 | // Related Topics Array Two Pointers Binary Search 👍 3691 👎 806
48 |
49 |
50 | package leetcodeProblem.leetcode.editor.en
51 |
52 | class TwoSumIiInputArrayIsSorted {
53 | fun solution() {
54 | }
55 |
56 | //below code will be used for submission to leetcode (using plugin of course)
57 | //leetcode submit region begin(Prohibit modification and deletion)
58 | class Solution {
59 | fun twoSum(numbers: IntArray, target: Int): IntArray {
60 | // 2,3,5,6,7,11,15 , 18 , 19 = 9
61 | var left = 0
62 | var right = numbers.size - 1
63 | while (left < right) {
64 | val sum = numbers[left] + numbers[right]
65 | if (sum > target) right--
66 | else if (sum < target) left++
67 | else return intArrayOf(left + 1, right + 1)
68 | }
69 | return intArrayOf(-1, -1)
70 | }
71 | }
72 | //leetcode submit region end(Prohibit modification and deletion)
73 |
74 | }
75 |
76 | fun main() {}
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
--------------------------------------------------------------------------------
/src/leetcodeProblem/leetcode/editor/en/UniqueBinarySearchTrees.kt:
--------------------------------------------------------------------------------
1 | //Given an integer n, return the number of structurally unique BST's (binary
2 | //search trees) which has exactly n nodes of unique values from 1 to n.
3 | //
4 | //
5 | // Example 1:
6 | //
7 | //
8 | //Input: n = 3
9 | //Output: 5
10 | //
11 | //
12 | // Example 2:
13 | //
14 | //
15 | //Input: n = 1
16 | //Output: 1
17 | //
18 | //
19 | //
20 | // Constraints:
21 | //
22 | //
23 | // 1 <= n <= 19
24 | //
25 | // Related Topics Math Dynamic Programming Tree Binary Search Tree Binary Tree ?
26 | //? 6049 👎 232
27 |
28 |
29 | package leetcodeProblem.leetcode.editor.en
30 |
31 | class UniqueBinarySearchTrees {
32 | fun solution() {
33 | }
34 |
35 | //below code will be used for submission to leetcode (using plugin of course)
36 | //leetcode submit region begin(Prohibit modification and deletion)
37 | class Solution {
38 | fun numTrees(n: Int): Int {
39 | var C: Long = 1
40 | for (i in 0 until n) {
41 | C = C * 2 * (2 * i + 1) / (i + 2)
42 | }
43 | return C.toInt()
44 | }
45 | }
46 | //leetcode submit region end(Prohibit modification and deletion)
47 |
48 | }
49 |
50 | fun main() {}
51 |
52 |
53 |
--------------------------------------------------------------------------------
/src/leetcode_daily_chalange/BestTimeToBuyAndSellStock3.kt:
--------------------------------------------------------------------------------
1 | package leetcode_daily_chalange
2 |
3 | class BestTimeToBuyAndSellStock3 {
4 | fun maxProfit(prices: IntArray): Int {
5 | if (prices.isEmpty()) return 0
6 | var s1 = -prices[0]
7 | var s2 = 0
8 | var s3 = Int.MIN_VALUE
9 | var s4 = 0
10 |
11 | for (i in 1 until prices.size) {
12 | s1 = maxOf(s1, -prices[i])
13 | s2 = maxOf(s2, s1 + prices[i])
14 | s3 = maxOf(s3, s2 - prices[i])
15 | s4 = maxOf(s4, s3 + prices[i])
16 | }
17 | return s4
18 | }
19 | }
--------------------------------------------------------------------------------
/src/leetcode_daily_chalange/BestTimeToBuyAndSellStockWithCoolDown.kt:
--------------------------------------------------------------------------------
1 | package leetcode_daily_chalange
2 |
3 | class BestTimeToBuyAndSellStockWithCoolDown {
4 | fun maxProfit(prices: IntArray): Int {
5 | var profitOne = 0
6 | var profitTwo = 0
7 | for (i in 1 until prices.size) {
8 | val temp = profitOne
9 | profitOne = maxOf(profitOne + prices[i] - prices[i - 1], profitTwo)
10 | profitTwo = maxOf(temp, profitTwo)
11 | }
12 | return maxOf(profitOne, profitTwo)
13 | }
14 | }
--------------------------------------------------------------------------------
/src/leetcode_daily_chalange/DiameterOfBinaryTree.kt:
--------------------------------------------------------------------------------
1 | package leetcode_daily_chalange
2 |
3 | import data_structure.tree.TreeNode
4 |
5 | class DiameterOfBinaryTree {
6 | fun diameterOfBinaryTree(root: TreeNode?): Int {
7 | var ans = 0
8 | fun dfs(root: TreeNode?): Int {
9 | if (root == null) return 0
10 | val l = dfs(root.left)
11 | val r = dfs(root.right)
12 | ans = maxOf(ans, l + r)
13 | return maxOf(l, r) + 1
14 | }
15 | dfs(root)
16 | return ans
17 | }
18 | }
--------------------------------------------------------------------------------
/src/leetcode_daily_chalange/FindAllDuplicatesinanArray.kt:
--------------------------------------------------------------------------------
1 | package leetcode_daily_chalange
2 |
3 |
4 | class FindAllDuplicatesInAnArray {
5 | // https://leetcode.com/problems/find-all-duplicates-in-an-array/
6 | fun findDuplicates(nums: IntArray): List {
7 | val mutableMap = mutableMapOf()
8 | val mutableListOf = mutableListOf()
9 | nums.forEach {
10 | if (mutableMap[it] == null) {
11 | mutableMap[it] = mutableMap.getOrDefault(it, 0) + 1
12 | } else if (mutableMap[it] == 1) {
13 | mutableListOf.add(it)
14 | }
15 | }
16 |
17 |
18 |
19 | return mutableListOf
20 | }
21 |
22 |
23 | }
--------------------------------------------------------------------------------
/src/leetcode_daily_chalange/LongestSumDivisibleByK.kt:
--------------------------------------------------------------------------------
1 | package leetcode_daily_chalange
2 |
3 | // https://leetcode.com/problems/subarray-sums-divisible-by-k/
4 |
5 | fun subArraysDivByK(nums: IntArray, k: Int): Int {
6 | if (nums.isEmpty()) return 0
7 | val mutableMap = mutableMapOf()
8 | var prefixSum = 0
9 | var ans = 0
10 | mutableMap[0] = 0
11 | for (i in nums.indices) {
12 | prefixSum += nums[i]
13 | var util = prefixSum % k
14 | if (util < 0) {
15 | util += k
16 | }
17 | if (mutableMap[util] != null) {
18 | ans += mutableMap[util]!! + 1
19 | mutableMap[util] = mutableMap[util]!! + 1
20 | } else mutableMap[util] = 0
21 | }
22 |
23 | return ans
24 |
25 | }
26 |
--------------------------------------------------------------------------------
/src/leetcode_daily_chalange/RangeBitWiseAnd.kt:
--------------------------------------------------------------------------------
1 | package leetcode_daily_chalange
2 |
3 | class RangeBitWiseAnd {
4 | fun rangeBitwiseAnd(left: Int, right: Int): Int {
5 | if (right == left) return left
6 |
7 | var n = right - left
8 |
9 | n = n or (n ushr 1)
10 | n = n or (n ushr 2)
11 | n = n or (n ushr 4)
12 | n = n or (n ushr 8)
13 | n = n or (n ushr 16)
14 |
15 | n = (n + 1)
16 | n = n ushr 1
17 | if (n < 0) return 0
18 |
19 | n = (n or (n - 1)).inv()
20 |
21 | return n and right and left
22 | }
23 | }
--------------------------------------------------------------------------------
/src/leetcode_study_badge/algorithm/Day1.kt:
--------------------------------------------------------------------------------
1 | package leetcode_study_badge.algorithm
2 |
3 | class Day1 {
4 | fun searchInsert(nums: IntArray, target: Int): Int {
5 | var left = 0
6 | var right = nums.size - 1
7 | if (nums[right] == target) return right
8 | if (nums[right] < target) return right + 1
9 | while (left < right) {
10 | val mid = left + (right - left) / 2
11 | if (nums[mid] == target) return mid
12 | if (nums[mid] < target && nums[mid + 1] > target) return mid + 1
13 | if (nums[mid] < target) {
14 | left = mid + 1
15 | } else {
16 | right = mid
17 | }
18 | }
19 | return 0
20 | }
21 | /* The isBadVersion API is defined in the parent class VersionControl.
22 | def isBadVersion(version: Int): Boolean = {} */
23 |
24 |
25 | fun firstBadVersion(n: Int): Int {
26 | return firstBadHelp(n, 0, n - 1)
27 | }
28 |
29 | private fun firstBadHelp(value: Int, first: Int, last: Int): Int {
30 | val mid = first + (last - first) / 2
31 | if (isBadVersion(last) && !isBadVersion(last - 1)) {
32 | return last
33 | }
34 |
35 | if (isBadVersion(mid)) {
36 | return firstBadHelp(value, first, mid)
37 | } else {
38 | return firstBadHelp(value, mid + 1, last)
39 | }
40 | }
41 |
42 | private fun isBadVersion(bad: Int): Boolean {
43 | val badReally = 5
44 | return badReally == bad
45 | }
46 |
47 | fun search(nums: IntArray, target: Int): Int {
48 | return binarySearch(nums, 0, nums.size - 1, target)
49 |
50 | }
51 |
52 | private fun binarySearch(
53 | intArray: IntArray, first: Int,
54 | last: Int, target: Int
55 | ): Int {
56 | if (last >= first) {
57 | val mid: Int = first + (last - first) / 2
58 | if (intArray[mid] == target) return mid
59 | if (intArray[mid] > target) return binarySearch(intArray, first, mid - 1, target)
60 | return binarySearch(intArray, mid + 1, last, target)
61 | }
62 |
63 | return -1
64 | }
65 |
66 | }
--------------------------------------------------------------------------------
/src/leetcode_study_badge/algorithm/Day11.kt:
--------------------------------------------------------------------------------
1 | package leetcode_study_badge.algorithm
2 |
3 | class Day11 {
4 | fun combine(n: Int, k: Int): List> {
5 | val combinations: MutableList> = mutableListOf()
6 | fun recurse(lo: Int, arity: Int, combination: List) {
7 | (lo..n).forEach {
8 | if (arity == 1) combinations.add(combination + it)
9 | else recurse(it + 1, arity - 1, combination + it)
10 | }
11 | }
12 | if (k > 0) recurse(1, k, emptyList())
13 | return combinations
14 | }
15 |
16 |
17 | }
18 |
19 | fun main() {
20 | val result = Day11().combine(4, 2)
21 | println(result)
22 | }
--------------------------------------------------------------------------------
/src/leetcode_study_badge/algorithm/Day2.kt:
--------------------------------------------------------------------------------
1 | package leetcode_study_badge.algorithm
2 |
3 | class Day2 {
4 | fun sortedSquares(nums: IntArray): IntArray {
5 | var right = nums.size - 1
6 | var left = 0
7 | val resultArray = IntArray(nums.size)
8 | var insertPosition = nums.size - 1
9 |
10 | while (left < right) {
11 | val leftValue = nums[left] * nums[left]
12 | val rightValue = nums[right] * nums[right]
13 | if (leftValue > rightValue) {
14 | resultArray[insertPosition] = leftValue
15 | insertPosition--
16 | left++
17 | } else if (rightValue > leftValue) {
18 | resultArray[insertPosition] = rightValue
19 | insertPosition--
20 | right--
21 | } else if (rightValue == leftValue) {
22 | resultArray[insertPosition] = rightValue
23 | insertPosition--
24 | resultArray[insertPosition] = leftValue
25 | insertPosition--
26 | right--
27 | left++
28 | }
29 | }
30 | println(resultArray.contentToString())
31 | if (left == right) {
32 | resultArray[insertPosition] = nums[left] * nums[left]
33 | }
34 |
35 | return resultArray
36 | }
37 |
38 | fun rotate(nums: IntArray, k: Int) {
39 | for (i in 0 until k) {
40 | var temp = nums[0]
41 | nums[0] = nums[nums.size - 1]
42 | for (a in 1 until nums.size) {
43 | var swap = nums[a]
44 | nums[a] = temp
45 | temp = swap
46 | }
47 | }
48 | }
49 |
50 | fun rotateTwoPointer(nums: IntArray, k: Int) {
51 |
52 | fun reverse(i: Int, j: Int) {
53 | var i = i; var j = j
54 |
55 | while (i < j) {
56 | nums[i] = nums[j].also { nums[j] = nums[i] }
57 | i++; j--
58 | }
59 | }
60 |
61 | val N = nums.size
62 | val k = k % N
63 |
64 | reverse(0, N - 1)
65 | reverse(0, k - 1)
66 | reverse(k, N - 1)
67 | }
68 |
69 |
70 |
71 | }
72 |
73 | fun main() {
74 | println(Day2().sortedSquares(intArrayOf(-7, -3, 2, 3, 11)).contentToString())
75 | val rotateArray = intArrayOf(1, 2, 3, 4, 5, 6, 7)
76 | println(rotateArray.contentToString())
77 | Day2().rotateTwoPointer(rotateArray, 3)
78 | println(rotateArray.contentToString())
79 | }
--------------------------------------------------------------------------------
/src/leetcode_study_badge/algorithm/Day3.kt:
--------------------------------------------------------------------------------
1 | package leetcode_study_badge.algorithm
2 |
3 | class Day3 {
4 | fun moveZeroesGood(nums: IntArray) {
5 | var lastNonZeroFoundAt = 0
6 | for (i in nums.indices) {
7 | if (nums[i] != 0) {
8 | nums[lastNonZeroFoundAt++] = nums[i]
9 | }
10 | }
11 | if (lastNonZeroFoundAt != 0) {
12 | for (i in lastNonZeroFoundAt until nums.size) {
13 | nums[i] = 0
14 | }
15 | }
16 |
17 | }
18 |
19 | fun twoSum(numbers: IntArray, target: Int): IntArray {
20 | var l = 0
21 | var r = numbers.size - 1
22 | while (l < r) {
23 | val sum = numbers[l] + numbers[r]
24 | if (sum > target) r--
25 | else if (sum < target) l++
26 | else return intArrayOf(l + 1, r + 1)
27 | }
28 | return intArrayOf(-1, -1)
29 | }
30 | }
31 |
32 | fun main() {
33 | val intArray = intArrayOf(
34 | 0,
35 | 0,
36 | 0,
37 | 0,
38 | 0,
39 | 0,
40 | 0,
41 | 0,
42 | 0,
43 | 0,
44 | 0,
45 | 0,
46 | 0,
47 | 0,
48 | 0,
49 | 0,
50 | 0,
51 | 0,
52 | 0,
53 | 0,
54 | 0,
55 | 0,
56 | 0,
57 | 0,
58 | 0,
59 | 0,
60 | 0,
61 | 0,
62 | 0,
63 | 0,
64 | 0,
65 | 1,
66 | 0,
67 | 3,
68 | 1,
69 | 2,
70 | 0,
71 | 0,
72 | 0,
73 | 0,
74 | 0,
75 | 0,
76 | 0,
77 | 0,
78 | 0,
79 | 0,
80 | 0
81 | )
82 | println(intArray.contentToString())
83 | }
--------------------------------------------------------------------------------
/src/leetcode_study_badge/algorithm/Day4.kt:
--------------------------------------------------------------------------------
1 | package leetcode_study_badge.algorithm
2 |
3 | class Day4 {
4 | fun reverseString(s: CharArray): Unit {
5 | var left = 0
6 | var right = s.size - 1
7 | while (left < right) {
8 | val temp = s[left]
9 | s[left] = s[right]
10 | s[right] = temp
11 | left++
12 | right--
13 | }
14 | }
15 |
16 | fun reverseWords(s: String): String {
17 | val result = s.toCharArray()
18 | var lastAssign = 0
19 | var left = 0
20 | while (left < s.length) {
21 | if (result[left].isWhitespace() || left == result.lastIndex) {
22 | var tempLeft = if (left == result.lastIndex) left else left - 1
23 | while (tempLeft > lastAssign) {
24 | val temp = result[tempLeft]
25 | result[tempLeft] = result[lastAssign]
26 | result[lastAssign] = temp
27 | lastAssign++
28 | tempLeft--
29 | }
30 | lastAssign = left + 1
31 | }
32 |
33 | left++
34 | }
35 | return String(result)
36 | }
37 | }
38 |
39 | fun main() {
40 | val charArray = charArrayOf('f', 'a', 'n', 'i', 'a', 'b', 'd', 'u', 'l', 'l', 'a', 'h')
41 | println(charArray.contentToString())
42 | Day4().reverseString(charArray)
43 | println(charArray.contentToString())
44 | }
--------------------------------------------------------------------------------
/src/leetcode_study_badge/algorithm/Day5.kt:
--------------------------------------------------------------------------------
1 | package leetcode_study_badge.algorithm
2 |
3 | import data_structure.linkedlist.SinglyLinkedList.Node
4 |
5 |
6 | class Day5 {
7 | fun middleNode(head: Node?): Node? {
8 | var current = head
9 | var size = 1
10 | while (current?.next != null) {
11 | size++
12 | current = current.next
13 | }
14 |
15 | if (size % 2 == 0) {
16 | size += 1
17 | }
18 | size /= 2
19 |
20 | current = head
21 | for (i in 1..size) {
22 | current = current?.next
23 | }
24 |
25 | return current
26 | }
27 |
28 | fun removeNthFromEnd(head: Node?, n: Int): Node? {
29 | var result = head
30 | var tempResult = result
31 | var current = head
32 | var size = 1
33 | while (current?.next != null) {
34 | size++
35 | current = current.next
36 | }
37 |
38 | size -= n
39 | if (size == 0) {
40 | tempResult = tempResult?.next
41 | } else {
42 | for (i in 1..size) {
43 | if (i == size) {
44 | result?.next = result?.next?.next
45 | } else {
46 | result = result?.next
47 | }
48 | }
49 | }
50 | return tempResult
51 | }
52 | }
--------------------------------------------------------------------------------
/src/leetcode_study_badge/algorithm/Day6.kt:
--------------------------------------------------------------------------------
1 | package leetcode_study_badge.algorithm
2 |
3 | class Day6 {
4 |
5 | fun checkInclusion(s1: String, s2: String): Boolean {
6 | if (s1.length > s2.length) return false
7 | val s1map = IntArray(26)
8 | val s2map = IntArray(26)
9 | for (i in s1.indices) {
10 | s1map[s1[i] - 'a']++
11 | s2map[s2[i] - 'a']++
12 | }
13 | for (i in 0 until s2.length - s1.length) {
14 | if (matches(s1map, s2map)) return true
15 | s2map[s2[i + s1.length] - 'a']++
16 | s2map[s2[i] - 'a']--
17 | }
18 | return matches(s1map, s2map)
19 | }
20 |
21 | private fun matches(s1map: IntArray, s2map: IntArray): Boolean {
22 | for (i in 0..25) {
23 | if (s1map[i] != s2map[i]) return false
24 | }
25 | return true
26 | }
27 |
28 | fun lengthOfLongestSubstring(s: String): Int {
29 | var longest = 0
30 | var currentRunStartIndex = 0
31 | val lastSeenIndices = IntArray(128)
32 | s.toCharArray().forEachIndexed { index, char ->
33 | with(char.code) {
34 | currentRunStartIndex = maxOf(lastSeenIndices[this], currentRunStartIndex)
35 | longest = maxOf(longest, index - currentRunStartIndex + 1)
36 | lastSeenIndices[this] = index + 1
37 |
38 | println(" index $index - $currentRunStartIndex and $longest , lastSeen ${lastSeenIndices[this]}")
39 | }
40 | }
41 | return longest
42 | }
43 |
44 | }
45 |
46 |
47 | fun main() {
48 | println(Day6().checkInclusion("fabi", "ibafsalsaila"))
49 | println(Day6().lengthOfLongestSubstring("abcabcbb"))
50 | }
--------------------------------------------------------------------------------
/src/leetcode_study_badge/algorithm/Day7.kt:
--------------------------------------------------------------------------------
1 | package leetcode_study_badge.algorithm
2 |
3 | class Day7 {
4 | fun floodFill(image: Array, sr: Int, sc: Int, newColor: Int): Array? {
5 | val color = image[sr][sc]
6 | if (color != newColor) dfs(image, sr, sc, color, newColor)
7 | return image
8 | }
9 |
10 | private fun dfs(image: Array, r: Int, c: Int, color: Int, newColor: Int) {
11 | if (image[r][c] == color) {
12 | image[r][c] = newColor
13 | if (r >= 1) dfs(image, r - 1, c, color, newColor)
14 | if (c >= 1) dfs(image, r, c - 1, color, newColor)
15 | if (r + 1 < image.size) dfs(image, r + 1, c, color, newColor)
16 | if (c + 1 < image[0].size) dfs(image, r, c + 1, color, newColor)
17 | }
18 | }
19 | }
--------------------------------------------------------------------------------
/src/leetcode_study_badge/data_structure/Day1.kt:
--------------------------------------------------------------------------------
1 | package leetcode_study_badge.data_structure
2 |
3 | import java.util.*
4 |
5 |
6 | class Day1 {
7 | fun singleNumber(nums: IntArray): Int {
8 | /*
9 | https://leetcode.com/problems/single-number/
10 |
11 | TC: O(N)
12 | SC: O(1)
13 | // XOR of A XOR A = 0, so all duplicates will cancel each other,
14 | // leaving the non duplicate
15 | */
16 | var singleNumber = 0
17 | nums.forEach {
18 | singleNumber = singleNumber.xor(it)
19 | }
20 | return singleNumber
21 |
22 | }
23 |
24 | fun majorityElement(nums: IntArray): Int {
25 | nums.sort()
26 | return nums[nums.size / 2]
27 | }
28 |
29 | /*
30 | // https://leetcode.com/problems/3sum/
31 | Input: nums = [-1,0,1,2,-1,-4]
32 | Output: [[-1,-1,2],[-1,0,1]]
33 | -4 -1 -1 0 1 2
34 |
35 |
36 | */
37 | fun threeSum(nums: IntArray): List> {
38 | var res = HashSet>()
39 | nums.sort()
40 | for (i in 0 until nums.lastIndex-1){
41 | var j = i+1
42 | var k = nums.lastIndex
43 | var tmp = - nums[i]
44 | while (j < k){
45 | var sum = nums[j] + nums[k]
46 | when {
47 | sum == tmp -> {
48 | res.add(listOf(nums[i],nums[j],nums[k]))
49 | j++
50 | k--
51 | }
52 | sum < tmp ->{
53 | j++
54 | }
55 | else ->{
56 | k--
57 | }
58 | }
59 | }
60 | }
61 | return res.toList()
62 | }
63 | }
64 |
65 | fun main() {
66 | println(Day1().singleNumber(intArrayOf(2, 2, 13, 5, 7, 8, 8, 7, 13)))
67 | println(Day1().threeSum(intArrayOf(-2,0,1,1,2)))
68 | }
--------------------------------------------------------------------------------
/src/leetcode_study_badge/data_structure/Day15.kt:
--------------------------------------------------------------------------------
1 | package leetcode_study_badge.data_structure
2 |
3 | import data_structure.tree.TreeNode
4 | import data_structure.tree.TreeTraversal
5 |
6 |
7 | class Day15 {
8 | fun sortedArrayToBST(nums: IntArray): TreeNode? {
9 | return partition(0, nums.size - 1, nums)
10 | }
11 |
12 | private fun partition(left: Int, right: Int, nums: IntArray): TreeNode? {
13 | val middle = left + (right - left) / 2
14 | if (left > right) return null
15 | val result: TreeNode? = TreeNode(nums[middle])
16 | result?.left = partition(left, middle - 1, nums)
17 | result?.right = partition(middle + 1, right, nums)
18 | return result
19 | }
20 |
21 | //https://leetcode.com/problems/construct-binary-tree-from-preorder-and-inorder-traversal/submissions/
22 | var preorderIndex = 0
23 | private var inorderIndexMap: HashMap = HashMap()
24 | fun buildTree(preorder: IntArray, inorder: IntArray): TreeNode? {
25 | preorderIndex = 0
26 |
27 | inorderIndexMap = HashMap()
28 | for (i in inorder.indices) {
29 | inorderIndexMap[inorder[i]] = i
30 | }
31 | return arrayToTree(preorder, 0, preorder.size - 1)
32 | }
33 |
34 | private fun arrayToTree(preorder: IntArray, left: Int, right: Int): TreeNode? {
35 |
36 | if (left > right) return null
37 |
38 | val rootValue = preorder[preorderIndex++]
39 | val root = TreeNode(rootValue)
40 |
41 |
42 | root.left = arrayToTree(preorder, left, inorderIndexMap[rootValue]!! - 1)
43 | root.right = arrayToTree(preorder, inorderIndexMap[rootValue]!! + 1, right)
44 | return root
45 | }
46 |
47 |
48 | }
49 |
50 | fun main() {
51 | val result = Day15().sortedArrayToBST(intArrayOf(1, 2, 3, 4, 5, 6))
52 | println(TreeTraversal().printLevelOrder(result))
53 | }
--------------------------------------------------------------------------------
/src/leetcode_study_badge/data_structure/Day16.kt:
--------------------------------------------------------------------------------
1 | package leetcode_study_badge.data_structure
2 |
3 | import data_structure.tree.TreeNode
4 |
5 | class Day16 {
6 | private lateinit var paths: MutableList>
7 |
8 | fun pathSum(root: TreeNode?, sum: Int): List> {
9 | paths = mutableListOf()
10 | root?.traverse(sum, listOf())
11 |
12 | return paths.toList()
13 | }
14 |
15 | private fun TreeNode.traverse(sum: Int, path: List) {
16 | if (this.left == null && this.right == null && sum - this.value == 0) {
17 | paths.add(path.insert(this.value))
18 | }
19 |
20 | if (this.left != null) {
21 | this.left?.traverse(sum - this.value, path.insert(this.value))
22 | }
23 |
24 | if (this.right != null) {
25 | this.right?.traverse(sum - this.value, path.insert(this.value))
26 | }
27 | }
28 |
29 | private fun List.insert(n: Int): List {
30 | val list = this.toMutableList()
31 | list.add(n)
32 | return list
33 | }
34 |
35 | fun deleteNode(root: TreeNode?, key: Int): TreeNode? {
36 | if (root == null) return root
37 | if (key < root.value) {
38 | root.left = deleteNode(root.left, key)
39 | } else if (key > root.value) {
40 | root.right = deleteNode(root.right, key)
41 | } else {
42 |
43 | if (root.left == null && root.right == null) {
44 | return null
45 | } else if (root.left != null && root.right != null) {
46 | val successor = minimumNode(root.right!!)
47 | root.right = deleteNode(root.right, successor)
48 | root.value = successor
49 | } else {
50 | return root.left ?: root.right
51 | }
52 | }
53 | return root
54 | }
55 |
56 | private fun minimumNode(root: TreeNode): Int {
57 | var node = root
58 | while (node.left != null) {
59 | node = node.left!!
60 | }
61 | return node.value
62 | }
63 | }
--------------------------------------------------------------------------------
/src/leetcode_study_badge/data_structure/Day17.kt:
--------------------------------------------------------------------------------
1 | package leetcode_study_badge.data_structure
2 |
3 | import data_structure.tree.TreeNode
4 |
5 | class Day17 {
6 | private var index = 0
7 | private var result = 0
8 |
9 | fun kthSmallest(root: TreeNode?, k: Int): Int {
10 | helper(root, k)
11 | return result
12 | }
13 |
14 | private fun helper(node: TreeNode?, k: Int) {
15 | if (node == null) return
16 |
17 | helper(node.left, k)
18 | if (++index == k) {
19 | result = node.value
20 | return
21 | }
22 | helper(node.right, k)
23 | }
24 |
25 | class BSTIterator(root: TreeNode?) {
26 | val stack = ArrayDeque()
27 |
28 | init {
29 | visitLeft(root)
30 | }
31 |
32 | private fun visitLeft(node: TreeNode?) {
33 | node?.run { stack.addLast(node) }
34 | node?.left?.run { visitLeft(node.left) }
35 | }
36 |
37 | fun next(): Int =
38 | stack.removeLast().let {
39 | visitLeft(it.right)
40 | it.value
41 | }
42 |
43 | fun hasNext(): Boolean =
44 | stack.isNotEmpty()
45 |
46 | }
47 |
48 | }
--------------------------------------------------------------------------------
/src/leetcode_study_badge/data_structure/Day18.kt:
--------------------------------------------------------------------------------
1 | package leetcode_study_badge.data_structure
2 |
3 | import data_structure.tree.TreeNode
4 | import java.util.*
5 |
6 | class Day18 {
7 | fun lowestCommonAncestor(root: TreeNode?, p: TreeNode?, q: TreeNode?): TreeNode? {
8 | if (root == null) return null
9 | if (root == p || root == q) return root
10 |
11 | val left = lowestCommonAncestor(root.left, p, q)
12 | val right = lowestCommonAncestor(root.right, p, q)
13 |
14 | return when {
15 | left != null && right != null -> root
16 | left != null -> left
17 | else -> right
18 | }
19 | }
20 |
21 | fun serialize(root: TreeNode?): String {
22 | val q = LinkedList()
23 | q.offer(root)
24 |
25 | val res = StringBuilder()
26 | var lastPos = 0
27 | while (!q.isEmpty()) {
28 | val node = q.poll()
29 | if (node == null) {
30 | res.append("null")
31 | } else {
32 | res.append(node.value)
33 | lastPos = res.length
34 | q.offer(node.left)
35 | q.offer(node.right)
36 | }
37 | res.append(",")
38 | }
39 | return res.substring(0..lastPos - 1)
40 | }
41 |
42 | // Decodes your encoded data to tree.
43 | fun deserialize(data: String): TreeNode? {
44 | if (data.isEmpty()) return null
45 | val list = data.split(",")
46 | val root = TreeNode(list[0].toInt())
47 | val q = ArrayDeque()
48 | q.offer(root)
49 |
50 | var i = 1
51 | while (i < list.size && !q.isEmpty()) {
52 | val node = q.poll()
53 | if (i < list.size && list[i] != "null") {
54 | node.left = TreeNode(list[i].toInt())
55 | q.offer(node.left)
56 | }
57 | i++
58 | if (i < list.size && list[i] != "null") {
59 | node.right = TreeNode(list[i].toInt())
60 | q.offer(node.right)
61 | }
62 | i++
63 | }
64 | return root
65 | }
66 | }
--------------------------------------------------------------------------------
/src/leetcode_study_badge/data_structure/Day19.kt:
--------------------------------------------------------------------------------
1 | package leetcode_study_badge.data_structure
2 |
3 | import java.util.*
4 |
5 | class Day19 {
6 | fun findJudge(n: Int, trust: Array): Int {
7 | val countWhomTrustI = IntArray(n)
8 | val countWhomTrustMe = IntArray(n)
9 | for ((who, whom) in trust) {
10 | countWhomTrustI[who - 1] = countWhomTrustI[who - 1] + 1
11 | countWhomTrustMe[whom - 1] = countWhomTrustMe[whom - 1] + 1
12 | }
13 | for (i in 0 until n) {
14 | if (countWhomTrustMe[i] == n- 1 && countWhomTrustI[i] == 0) {
15 | return i + 1
16 | }
17 | }
18 | return -1
19 | }
20 |
21 | fun findSmallestSetOfVertices(n: Int, edges: List>, inDegree: IntArray = IntArray(n)) =
22 | edges.map { inDegree[it[1]]++ }
23 | .run { inDegree.withIndex().filter { it.value == 0 }.map { it.index } }
24 | fun canVisitAllRooms(rooms: List>): Boolean {
25 | val visited = mutableSetOf()
26 | val queue = LinkedList().also { it.offer(0); visited.add(0) }
27 | while (queue.isNotEmpty()) {
28 | val room = queue.poll()
29 | for (neighbor in rooms[room]) {
30 | if (!visited.contains(neighbor)) {
31 | visited.add(neighbor)
32 | queue.offer(neighbor)
33 | }
34 | }
35 | }
36 | return visited.size == rooms.size
37 | }
38 | }
--------------------------------------------------------------------------------
/src/leetcode_study_badge/data_structure/Day2.kt:
--------------------------------------------------------------------------------
1 | package leetcode_study_badge.data_structure
2 |
3 | import java.util.*
4 |
5 |
6 | class Day2 {
7 | fun sortColors(nums: IntArray) {
8 | var one = 0
9 | var two = 0
10 | var insertPosition = -1
11 |
12 | repeat(nums.count()) {
13 | if (nums[it] == 0) {
14 | insertPosition++
15 | nums[insertPosition] = 0
16 | } else if (nums[it] == 1) {
17 | one++
18 | } else {
19 | two++
20 | }
21 | }
22 |
23 | repeat(one) {
24 | insertPosition++
25 | nums[insertPosition] = 1
26 | }
27 | repeat(two) {
28 | insertPosition++
29 | nums[insertPosition] = 2
30 | }
31 |
32 | }
33 |
34 | fun merge(intervals: Array): Array {
35 | Arrays.sort(
36 | intervals
37 | ) { a: IntArray, b: IntArray -> a[0].compareTo(b[0]) }
38 | val merged = mutableListOf()
39 | // [0, 3][0, 1][0, 2][1, 9][2, 5][10, 11][12, 20][19, 20]
40 | for (interval in intervals) {
41 | println(interval.contentToString())
42 | if (merged.isEmpty() || merged.last()[1] < interval[0]) {
43 | merged.add(interval)
44 | } else {
45 | merged.last()[1] = maxOf(merged.last()[1], interval[1])
46 | }
47 | }
48 | return merged.toTypedArray()
49 | }
50 | }
51 |
52 |
53 | class MyHashMap() {
54 | /** Initialize your data structure here. */
55 | private val data = arrayOfNulls(1000001)
56 |
57 | /** value will always be non-negative. */
58 | fun put(key: Int, value: Int) {
59 | data[key] = value
60 | }
61 |
62 | /** Returns the value to which the specified key is mapped, or -1 if this map contains no mapping for the key */
63 | fun get(key: Int): Int {
64 | return data[key] ?: -1
65 | }
66 |
67 | /** Removes the mapping of the specified value key if this map contains a mapping for the key */
68 | fun remove(key: Int) {
69 | data[key] = null
70 | }
71 |
72 | }
73 |
74 | fun main() {
75 | val intArray = intArrayOf(2, 0, 2, 1, 1, 0)
76 | Day2().sortColors(intArray)
77 | val intArrayIntervals = arrayOf(
78 | intArrayOf(1, 4),
79 | intArrayOf(0, 4)
80 | )
81 | val result = Day2().merge(intArrayIntervals)
82 | result.forEach {
83 | print(it.contentToString())
84 | }
85 | println(intArray.contentToString())
86 | }
87 |
--------------------------------------------------------------------------------
/src/leetcode_study_badge/data_structure/Day20.kt:
--------------------------------------------------------------------------------
1 | package leetcode_study_badge.data_structure
2 |
3 | class Day20 {
4 | fun findKthLargest(nums: IntArray, k: Int) = nums.sortedDescending()[k - 1]
5 | fun topKFrequent(nums: IntArray, k: Int): IntArray {
6 | val map = mutableMapOf()
7 | nums.forEach { map[it] = map.getOrDefault(it, 0) + 1 }
8 |
9 | val uniques = mutableListOf()
10 | val pairs = map.toList().sortedByDescending { it.second }
11 | pairs.forEach {
12 | while (uniques.size < k) {
13 | uniques.add(it.first)
14 | break
15 | }
16 | }
17 |
18 | return uniques.toIntArray()
19 | }
20 | }
--------------------------------------------------------------------------------
/src/leetcode_study_badge/data_structure/Day21.kt:
--------------------------------------------------------------------------------
1 | package leetcode_study_badge.data_structure
2 |
3 | class Day21 {
4 | fun frequencySort(s: String): String {
5 | return s
6 | .split("")
7 | .filter { it -> it != "" }
8 | .groupingBy { it }
9 | .eachCount()
10 | .toList()
11 | .sortedBy { it.second }
12 | .reversed()
13 | .map { it ->
14 | var t = ""
15 | for (i in 0 until it.second.toInt()) {
16 | t = t + it.first
17 | }
18 | t
19 | }
20 | .joinToString("")
21 | }
22 |
23 | fun kClosest(points: Array, K: Int): Array {
24 | var l = MutableList(points.size) {
25 | intArrayOf(
26 | points[it][0] * points[it][0] + points[it][1] * points[it][1],
27 | points[it][0],
28 | points[it][1]
29 | )
30 | }.apply { this.sortWith(compareBy({ it[0] })) }
31 | return Array(K) { intArrayOf(l[it][1], l[it][2]) }
32 | }
33 | }
--------------------------------------------------------------------------------
/src/leetcode_study_badge/data_structure/Day4.kt:
--------------------------------------------------------------------------------
1 | package leetcode_study_badge.data_structure
2 |
3 | class Day4 {
4 | fun searchMatrix(matrix: Array, target: Int): Boolean {
5 |
6 | for (i in matrix.indices) {
7 | if (matrix[i][0] == target) return true
8 | if (matrix[i][0] > target) {
9 | return false
10 | } else if (matrix[i][0] < target) {
11 | var left = 0
12 | var right = matrix[i].size - 1
13 | while (left <= right) {
14 | val mid = left + (right - left) / 2
15 | if (matrix[i][mid] == target) {
16 | return true
17 | } else if (target > matrix[i][mid]) {
18 | left = mid + 1
19 | } else {
20 | right = mid - 1
21 | }
22 | }
23 | }
24 | }
25 |
26 |
27 |
28 |
29 | return false
30 | }
31 |
32 | fun eraseOverlapIntervals(intervals: Array): Int {
33 | if (intervals.isEmpty()) return 0
34 | intervals.sortWith(compareBy({ it.first() }, { it.last() }))
35 | var count = 0
36 | var temp = intervals.first().last()
37 | for (i in 1..intervals.lastIndex) {
38 | if (intervals[i].first() >= temp) {
39 | temp = intervals[i].last()
40 | } else {
41 | count++
42 | temp = minOf(intervals[i].last(), temp)
43 | }
44 | }
45 | return count
46 | }
47 | }
48 |
49 | fun main() {
50 | val matrix =
51 | arrayOf(
52 | intArrayOf(5),
53 | intArrayOf(6),
54 | )
55 | println(Day4().searchMatrix(matrix, 6))
56 | }
--------------------------------------------------------------------------------
/src/leetcode_study_badge/data_structure/Day5.kt:
--------------------------------------------------------------------------------
1 | package leetcode_study_badge.data_structure
2 |
3 |
4 | class Day5 {
5 | fun productExceptSelf(nums: IntArray): IntArray {
6 | val newNums = IntArray(nums.size) { 1 }
7 | var startIndexValue = 1
8 | var endIndexValue = 1
9 | for (i in nums.indices) {
10 | newNums[i] *= startIndexValue
11 | newNums[nums.lastIndex - i] = endIndexValue
12 | startIndexValue *= nums[i]
13 | endIndexValue *= nums[nums.lastIndex - i]
14 | }
15 |
16 | return nums
17 | }
18 |
19 |
20 | fun subarraySum(nums: IntArray, k: Int): Int {
21 | val hashMap = HashMap()
22 | var counter = 0
23 | var sum = 0
24 | for (i in nums) {
25 | sum += nums[i]
26 | if (hashMap.containsKey(sum - k)) counter += hashMap[sum - k] as Int
27 | hashMap[sum] = hashMap.getOrDefault(sum, 0) + 1
28 |
29 | counter++
30 | }
31 | return counter
32 | }
33 |
34 | }
35 |
36 | fun main() {
37 | Day5().productExceptSelf(intArrayOf(1, 2, 3, 4))
38 | }
--------------------------------------------------------------------------------
/src/leetcode_study_badge/data_structure/Day6.kt:
--------------------------------------------------------------------------------
1 | package leetcode_study_badge.data_structure
2 |
3 | class Day6 {
4 | fun addStrings(num1: String, num2: String): String {
5 | var numbers1 = num1.length - 1
6 | var numbers2 = num2.length - 1
7 | var carry: Int = 0
8 | val stringResult = StringBuilder()
9 | while (numbers1 >= 0 || numbers2 >= 0) {
10 | val n1 = if (numbers1 >= 0) num1[numbers1] - '0' else 0
11 | val n2 = if (numbers2 >= 0) num2[numbers2] - '0' else 0
12 | val result = (n1 + n2 + carry) % 10
13 | carry = (n1 + n2 + carry) / 10
14 | stringResult.append(result)
15 | numbers1--
16 | numbers2--
17 | }
18 |
19 |
20 | if (carry != 0) stringResult.append(carry)
21 |
22 | return stringResult.reverse().toString()
23 | }
24 |
25 | fun longestPalindrome(s: String): Int {
26 | val count = IntArray(128)
27 | for (c in s.toCharArray()) count[c - '0']++
28 | var ans = 0
29 | for (v in count) {
30 | ans += v / 2 * 2
31 | }
32 | if (ans < s.length) ans++
33 | return ans
34 | }
35 | }
36 |
37 | fun main() {
38 | println(Day6().longestPalindrome("abcdefga"))
39 | }
--------------------------------------------------------------------------------
/src/leetcode_study_badge/data_structure/Day7.kt:
--------------------------------------------------------------------------------
1 | package leetcode_study_badge.data_structure
2 |
3 | import java.util.*
4 |
5 |
6 | class Day7 {
7 | fun wordPattern(pattern: String, s: String): Boolean {
8 | val list = s.split(" ")
9 | if (list.size != pattern.length) return false
10 |
11 | val map = mutableMapOf()
12 | pattern.forEachIndexed { i, ch ->
13 | when (map.containsKey(ch)) {
14 | true -> if (map[ch] != list[i]) return false
15 | false -> {
16 | if (map.containsValue(list[i])) return false
17 | map[ch] = list[i]
18 | }
19 | }
20 | }
21 |
22 | return true
23 | }
24 |
25 | fun canSeePersonsCount(heights: IntArray): IntArray {
26 | // descending monotonic stack
27 | val res = IntArray(heights.size)
28 | val stk = Stack() // [height, index]
29 | for (i in heights.indices) {
30 | val h = heights[i]
31 | while (!stk.isEmpty() && stk.peek()[0] < h) {
32 | val prev = stk.pop()[1]
33 | res[prev]++ // prev shorter can see taller
34 | }
35 | if (!stk.isEmpty()) {
36 | res[stk.peek()[1]]++ // prev taller can see shorter
37 | }
38 | println(res.contentToString())
39 | stk.push(intArrayOf(h, i))
40 | }
41 | return res
42 | }
43 | }
44 |
45 | fun main() {
46 | println(Day7().wordPattern("jsj", "jquery s jquery"))
47 | Day7().canSeePersonsCount(intArrayOf(10, 6, 8, 5, 11, 9))
48 | }
--------------------------------------------------------------------------------
/src/leetcode_study_badge/data_structure/Day8.kt:
--------------------------------------------------------------------------------
1 | package leetcode_study_badge.data_structure
2 |
3 | class Day8 {
4 | fun groupAnagrams(strs: Array): List> {
5 |
6 | val hashToStrs = HashMap>()
7 | for (str in strs) {
8 | hashToStrs.getOrPut(hash(str)) { mutableListOf() }.add(str)
9 | }
10 |
11 | return hashToStrs.values.toList()
12 | }
13 |
14 | private fun hash(str: String): Int {
15 | val freqs = IntArray(26) { 0 }
16 | for (ch in str) {
17 | ++freqs[ch - 'a']
18 | }
19 | return freqs.contentHashCode()
20 | }
21 |
22 | // One line solution
23 | fun groupAnagramsOneLine(strs: Array): List> = mutableMapOf>().apply {
24 | strs.forEach {
25 | getOrPut(it.toCharArray().sorted().joinToString("")) { mutableListOf() }.add(it)
26 | }
27 | }.values.toList()
28 |
29 |
30 | fun multiply(num1: String, num2: String): String {
31 | if ("0" == num1 || "0" == num2)
32 | return "0"
33 |
34 | val list = Array(num1.length + num2.length - 1){0}
35 |
36 | for (i in num1.length - 1 downTo 0) {
37 | for (j in num2.length - 1 downTo 0) {
38 | list[i + j] += (num1[i] - '0') * (num2[j] - '0')
39 | }
40 | }
41 |
42 | for (i in list.size - 1 downTo 1) {
43 | list[i - 1] += list[i] / 10
44 |
45 | list[i] %= 10
46 |
47 | }
48 |
49 |
50 | val builder = StringBuilder()
51 | list.forEach {
52 | builder.append(it)
53 | }
54 |
55 | return builder.toString()
56 | }
57 |
58 | }
59 |
60 | fun main() {
61 | val result = Day8().groupAnagramsOneLine(arrayOf("eat", "tea", "tan", "ate", "nat", "bat"))
62 |
63 | println(Day8().multiply("145","12"))
64 | }
65 |
--------------------------------------------------------------------------------
/src/leetcode_study_badge/dynamic_programming/Day1.kt:
--------------------------------------------------------------------------------
1 | package leetcode_study_badge.dynamic_programming
2 |
3 | class Day1 {
4 | fun tribonacci(n: Int): Int {
5 | if (n == 0) return 0
6 | if (n <= 2) return 1
7 | var one = 0
8 | var two = 1
9 | var three = 1
10 | var temp3 = 0
11 | var temp2 = 0
12 | for (i in 3..n) {
13 | temp3 = three
14 | three += two + one
15 | temp2 = two
16 | two = temp3
17 | one = temp2
18 | }
19 |
20 | return three
21 | }
22 | private val lookupTable: IntArray = IntArray(31)
23 |
24 | fun fib(n: Int): Int {
25 | if (n <= 1) {
26 | lookupTable[n] = n
27 | } else {
28 | lookupTable[n] = fib(n - 1) + fib(n - 2)
29 | }
30 |
31 | return lookupTable[n]
32 | }
33 | }
--------------------------------------------------------------------------------
/src/leetcode_study_badge/dynamic_programming/Day2.kt:
--------------------------------------------------------------------------------
1 | package leetcode_study_badge.dynamic_programming
2 |
3 |
4 | class Day2 {
5 | // https://leetcode.com/problems/climbing-stairs/
6 | // Bottom up
7 | fun climbStairs(n: Int): Int {
8 | if (n <= 3) return n
9 | var one = 1
10 | var two = 2
11 | var result = one + two
12 | for (i in 3..n) {
13 | result = one + two
14 | one = two
15 | two = result
16 | }
17 | return result
18 | }
19 |
20 | // in place
21 | fun minCostClimbingStairs(cost: IntArray): Int {
22 | for (i in cost.size - 1 downTo 0) {
23 | if (i == cost.lastIndex || i == cost.lastIndex - 1) cost[i] += 0
24 | else cost[i] += minOf(cost[i + 1], cost[i + 2])
25 | }
26 | return minOf(cost[0], cost[1])
27 | }
28 |
29 | // +dp
30 | fun minCost(cost: IntArray): Int {
31 | val n: Int = cost.size
32 | val dp = IntArray(n + 1)
33 | dp[n - 1] = cost[n - 1]
34 | for (i in n - 2 downTo 0) {
35 | dp[i] = cost[i] + minOf(dp[i + 1], dp[i + 2])
36 | }
37 | return minOf(dp[0], dp[1])
38 | }
39 | }
40 |
41 | fun main() {
42 | println(Day2().minCostClimbingStairs(intArrayOf(1, 100, 1, 1, 1, 100, 1, 1, 100, 1)))
43 | }
--------------------------------------------------------------------------------
/src/leetcode_study_badge/dynamic_programming/Day4.kt:
--------------------------------------------------------------------------------
1 | package leetcode_study_badge.dynamic_programming
2 |
3 | class Day4 {
4 | fun canJump(nums: IntArray): Boolean {
5 | if (nums.size == 1) return true
6 | if (nums[0] == 0) return false
7 | val dp = IntArray(nums.size)
8 | dp[0] = nums[0]
9 | for (i in 1 until nums.size) {
10 | dp[i] = maxOf(dp[i - 1] - 1, nums[i])
11 | if (dp[i] == 0 && i != nums.lastIndex) return false
12 | }
13 |
14 | return true
15 | }
16 |
17 |
18 | fun canJumpO1space(nums: IntArray): Boolean {
19 | if (nums.size == 1) return true
20 | if (nums[0] == 0) return false
21 | var state = nums[0]
22 | for (i in 1 until nums.size) {
23 | state = maxOf(state - 1, nums[i])
24 | if (state == 0 && i != nums.lastIndex) return false
25 | }
26 |
27 | return true
28 | }
29 |
30 |
31 | fun canJump2(nums: IntArray): Int {
32 | if (nums.size == 1) return 0
33 | if (nums.size == 2) return 2
34 |
35 | var state = nums[0]
36 | var carry = 1
37 | var counter = 2
38 | for (i in 1 until nums.size) {
39 | state -= 1
40 | carry = maxOf(carry, nums[i])
41 |
42 | if (nums[i] + i == nums.lastIndex) {
43 | counter++
44 | break
45 | } else {
46 | if (state == 0 && nums[i] + i == nums.lastIndex) {
47 | state = carry
48 | counter += 2
49 | }
50 | }
51 | }
52 |
53 | return counter
54 | }
55 |
56 | fun jump(nums: IntArray): Int {
57 | var curr = 0
58 | var step = 0
59 | var last = 0
60 | for (i in nums.indices) {
61 | if (i > last) {
62 | last = curr
63 | step++
64 | if (last >= nums.size) return step
65 | }
66 | curr = maxOf(curr, i + nums[i])
67 | }
68 | return step
69 | }
70 |
71 | fun jump2(nums: IntArray): Int { // dp solution
72 | val n = nums.size
73 | val dp = Array(n) { 0 }
74 | dp[0] = 0
75 | for (i in 1 until n) {
76 | var curr = Integer.MAX_VALUE
77 | for (j in i - 1 downTo 0) {
78 | if (nums[j] >= i - j)
79 | curr = minOf(curr, dp[j] + 1)
80 | }
81 | dp[i] = curr
82 | }
83 | return dp[n - 1]
84 | }
85 |
86 | }
87 |
88 | fun main() {
89 | println(Day4().canJump2(intArrayOf(1, 2, 3)))
90 | }
--------------------------------------------------------------------------------
/src/leetcode_study_badge/dynamic_programming/Day5.kt:
--------------------------------------------------------------------------------
1 | package leetcode_study_badge.dynamic_programming
2 |
3 | class Day5 {
4 | fun maxSubArray(nums: IntArray): Int {
5 | val dp = IntArray(nums.size)
6 | dp[0] = maxOf(nums[0] + nums[nums.size - 1], nums[0])
7 | var maxDP = dp[0]
8 | for (i in 1 until nums.size) {
9 | if (i == nums.lastIndex) {
10 | dp[i] = maxOf(dp[i - 1],nums[i] + nums[i - 1])
11 | } else {
12 | dp[i] = maxOf(dp[i - 1] + nums[i] , nums[i] + nums[i - 1])
13 | }
14 | maxDP = maxOf(maxDP, dp[i], nums[i])
15 | }
16 | return maxDP
17 |
18 | }
19 | }
20 |
21 | fun main() {
22 | println(Day5().maxSubArray(intArrayOf(-2, 2, -2, 9)))
23 |
24 | println(Day5().maxSubArray(intArrayOf(-5, 3, 5)))
25 | }
--------------------------------------------------------------------------------
/src/leetcode_study_badge/dynamic_programming/Day6.kt:
--------------------------------------------------------------------------------
1 | package leetcode_study_badge.dynamic_programming
2 |
3 | class Day6 {
4 | fun maxProduct(nums: IntArray): Int {
5 | if (nums.isEmpty()) return 0
6 |
7 | var min = nums[0]
8 | var max = nums[0]
9 | var res = nums[0]
10 |
11 | for (i in 1 until nums.size) {
12 | val tmp = max
13 | val n = nums[i]
14 |
15 |
16 | max = maxOf(max * n, maxOf(min * n, n))
17 | min = minOf(tmp * n, minOf(min * n, n))
18 |
19 | res = maxOf(res, max)
20 | }
21 |
22 | return res
23 | }
24 |
25 | fun getMaxLen(nums: IntArray): Int {
26 | val len: Int = nums.size
27 | var max = 0
28 | val fneg = IntArray(len + 1) // the length of longest negative product sub-array
29 |
30 | val fpos = IntArray(len + 1) // the length of longest positive product sub-array
31 |
32 |
33 | for (i in 1..len) {
34 | if (nums[i - 1] > 0) {
35 | // when positive subarray meets a positive number, the length will be increased by one at all case
36 | // the negative subarray will be increased only if it is not empty.
37 | fpos[i] = fpos[i - 1] + 1
38 | fneg[i] = if (fneg[i - 1] > 0) fneg[i - 1] + 1 else 0
39 | } else if (nums[i - 1] < 0) {
40 | // the positive subarray will be increased only if the previous product is negative
41 | // the negative subarray will be increased only if the previous product is positive
42 | fpos[i] = if (fneg[i - 1] > 0) fneg[i - 1] + 1 else 0
43 | fneg[i] = fpos[i - 1] + 1
44 | }
45 | max = maxOf(fpos[i], max)
46 | }
47 | return max
48 | }
49 |
50 | fun maxProfit(prices: IntArray): Int {
51 | var profitOne = 0
52 | var profitTwo = 0
53 | for (i in 1 until prices.size) {
54 | val temp = profitOne
55 | profitOne = maxOf(profitOne + prices[i] - prices[i - 1], profitTwo)
56 | profitTwo = maxOf(temp, profitTwo)
57 | }
58 | return maxOf(profitOne, profitTwo)
59 | }
60 | }
61 |
62 | fun main() {
63 | println(Day6().getMaxLen(intArrayOf(2, 8, 2, 3, 5, 4, -2, 10, 0, 1, 2, -3, 4, 5, 6, 7, 8, -9, 10)))
64 | }
--------------------------------------------------------------------------------
/src/solid_principle/DependencyInversion.kt:
--------------------------------------------------------------------------------
1 | package solid_principle
2 |
3 | class BeforeDependencyInversion(){
4 | class Car(private val engine: Engine) {
5 | fun start() {
6 | engine.start()
7 | }
8 | }
9 |
10 | class Engine {
11 | fun start() {}
12 | }
13 |
14 | class DieselEngine {
15 | fun start() {}
16 | }
17 |
18 | }
19 |
20 | class DependencyInversion {
21 | interface EngineInterface {
22 | fun start()
23 | }
24 |
25 | class Car(private val engine: EngineInterface) {
26 | fun start() {
27 | engine.start()
28 | }
29 | }
30 |
31 | class PetrolEngine : EngineInterface {
32 | override fun start() {}
33 | }
34 |
35 | class HybridEngine: EngineInterface {
36 | override fun start() {}
37 | }
38 |
39 | class DieselEngine : EngineInterface {
40 | override fun start() {}
41 | }
42 | }
--------------------------------------------------------------------------------
/src/solid_principle/InterfaceSegregation.kt:
--------------------------------------------------------------------------------
1 | package solid_principle
2 |
3 | class BeforeInterfaceSegregation {
4 | interface VehicleInterface {
5 | fun drive()
6 | fun stop()
7 | fun refuel()
8 | fun openDoors()
9 | }
10 |
11 |
12 | class Motorcycle : VehicleInterface {
13 | // Can be implemented
14 | override fun drive() {}
15 | override fun stop() {}
16 | override fun refuel() {}
17 |
18 |
19 | //Pain point
20 | // Can not be implemented
21 | override fun openDoors() {}
22 | }
23 | }
24 |
25 | class InterfaceSegregation {
26 |
27 | interface VehicleInterface {
28 | fun drive()
29 | fun stop()
30 | fun refuel()
31 | }
32 |
33 | interface DoorInterface {
34 | fun openDoors()
35 | }
36 |
37 | class Car : VehicleInterface, DoorInterface {
38 | override fun drive() {}
39 | override fun stop() {}
40 | override fun refuel() {}
41 | override fun openDoors() {}
42 | }
43 |
44 | class Motorcycle : VehicleInterface {
45 | override fun drive() {}
46 | override fun stop() {}
47 | override fun refuel() {}
48 | }
49 | }
--------------------------------------------------------------------------------
/src/solid_principle/LiskovSubstitution.kt:
--------------------------------------------------------------------------------
1 | package solid_principle
2 |
3 | import java.util.*
4 |
5 | class BeforeLiskovSubstitution() {
6 | abstract class Product {
7 | abstract fun getName(): String?
8 | abstract fun getExpiredDate(): Date?
9 |
10 | /**
11 | * Function to get all of information about product
12 | */
13 | fun getProductInfo() {
14 | // some magic code
15 | }
16 | }
17 |
18 | class Vegetable : Product() {
19 |
20 | override fun getName(): String {
21 | return "Broccoli"
22 | }
23 |
24 | override fun getExpiredDate(): Date {
25 | return Date()
26 | }
27 | }
28 |
29 |
30 | class Smartphone : Product() {
31 |
32 | override fun getName(): String {
33 | return "Samsung S10+ Limited Edition"
34 | }
35 |
36 | override fun getExpiredDate(): Date {
37 | return Date() // ???????
38 | }
39 | }
40 | }
41 |
42 | class LiskovSubstitution {
43 | abstract class Product {
44 | abstract fun getName(): String
45 |
46 | /**
47 | * Function to get all of information about product
48 | */
49 | fun getProductInfo() {
50 | // some magic code
51 | }
52 | }
53 |
54 | abstract class FoodProduct : Product() {
55 | abstract fun getExpiredDate(): Date
56 | }
57 |
58 | class Smartphone : Product() {
59 |
60 | override fun getName(): String {
61 | return "Samsung S10+ Limited Edition"
62 | }
63 | }
64 |
65 | class Vegetable : FoodProduct() {
66 |
67 | override fun getName(): String {
68 | return "Broccoli"
69 | }
70 |
71 | override fun getExpiredDate(): Date {
72 | return Date()
73 | }
74 | }
75 | }
--------------------------------------------------------------------------------
/src/solid_principle/OpenClose.kt:
--------------------------------------------------------------------------------
1 | package solid_principle
2 |
3 | class BeforeOpenClose() {
4 | open class Cinema(val price: Double)
5 |
6 | class StandardCinema(price: Double) : Cinema(price)
7 |
8 | class DeluxeCinema(price: Double) : Cinema(price)
9 |
10 | class PremiumCinema(price: Double) : Cinema(price)
11 |
12 |
13 | class CinemaCalculations {
14 | fun calculateAdminFee(cinema: Cinema): Double {
15 | return if (cinema is StandardCinema) {
16 | cinema.price * 10 / 100
17 | } else if (cinema is DeluxeCinema) {
18 | cinema.price * 12 / 100
19 | } else if (cinema is PremiumCinema) {
20 | cinema.price * 20 / 100
21 | } else 0.0
22 | }
23 | }
24 | }
25 |
26 |
27 | class OpenClose {
28 | abstract class Cinema(val price: Double) {
29 | abstract fun calculateAdminFee(): Double
30 | }
31 |
32 | class StandardCinema(price: Double) : Cinema(price) {
33 | override fun calculateAdminFee(): Double {
34 | return price * 10 / 100
35 | }
36 | }
37 |
38 | class DeluxeCinema(price: Double) : Cinema(price) {
39 | override fun calculateAdminFee(): Double {
40 | return price * 12 / 100
41 | }
42 | }
43 |
44 | }
--------------------------------------------------------------------------------
/src/solid_principle/SingleResponsibility.kt:
--------------------------------------------------------------------------------
1 | package solid_principle
2 |
3 | class BeforeSRP() {
4 | class Order {
5 | fun calculateTotalSum() {/*...*/
6 | }
7 |
8 | fun getItems() {/*...*/
9 | }
10 |
11 | fun getItemCount() {/*...*/
12 | }
13 |
14 | fun addItem(item: Item) {/*...*/
15 | }
16 |
17 | fun deleteItem(item: Item) {/*...*/
18 | }
19 |
20 | fun printOrder() {/*...*/
21 | }
22 |
23 | fun showOrder() {/*...*/
24 | }
25 |
26 | fun getDailyHistory() {/*...*/
27 | }
28 |
29 | fun getMonthlyHistory() {/*...*/
30 | }
31 |
32 | }
33 |
34 | class Item
35 | }
36 |
37 | class SingleResponsibility {
38 | class Order {
39 | fun calculateTotalSum() {}
40 | fun getItems() {}
41 | fun getItemCount() {}
42 | fun addItem(item: Item) {}
43 | fun deleteItem(item: Item) {}
44 | }
45 |
46 | class Item
47 | class OrderHistory {
48 | fun getDailyHistory() {}
49 | fun getMonthlyHistory() {}
50 | }
51 |
52 | class OrderViewer {
53 | fun printOrder(order: Order) {}
54 | fun showOrder(order: Order) {}
55 | }
56 | }
--------------------------------------------------------------------------------