├── .gitignore ├── gradle.properties ├── settings.gradle.kts ├── images └── banner.png ├── gradle └── wrapper │ ├── gradle-wrapper.jar │ └── gradle-wrapper.properties ├── src ├── main │ └── kotlin │ │ ├── array │ │ ├── ArrayLeftRotate.kt │ │ ├── ArrayRightRotate.kt │ │ ├── ArrayMinMax.kt │ │ ├── ArrayReverse.kt │ │ └── README.md │ │ ├── string │ │ ├── StringReverse.kt │ │ └── README.md │ │ ├── trie │ │ └── README.md │ │ ├── matrix │ │ └── README.md │ │ ├── bitmanipulation │ │ └── README.md │ │ ├── heap │ │ └── README.md │ │ ├── backtracking │ │ └── README.md │ │ ├── binarysearchtree │ │ └── README.md │ │ ├── searchingandsorting │ │ └── README.md │ │ ├── greedy │ │ └── README.md │ │ ├── linkedlist │ │ └── README.md │ │ ├── binarytree │ │ └── README.md │ │ ├── stackandqueue │ │ └── README.md │ │ ├── graph │ │ └── README.md │ │ └── dynamicprogramming │ │ └── README.md └── test │ └── kotlin │ ├── string │ └── StringReverseTest.kt │ └── array │ ├── ArrayMinMaxTest.kt │ ├── ArrayLeftRotateTest.kt │ ├── ArrayRightRotateTest.kt │ └── ArrayReverseTest.kt ├── .github └── workflows │ └── gradle-ci.yml ├── licence ├── gradlew.bat ├── README.md └── gradlew /.gitignore: -------------------------------------------------------------------------------- 1 | .gradle 2 | build 3 | .idea -------------------------------------------------------------------------------- /gradle.properties: -------------------------------------------------------------------------------- 1 | kotlin.code.style=official 2 | -------------------------------------------------------------------------------- /settings.gradle.kts: -------------------------------------------------------------------------------- 1 | 2 | rootProject.name = "dsa" 3 | 4 | -------------------------------------------------------------------------------- /images/banner.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alidehkhodaei/data-structures-and-algorithms/HEAD/images/banner.png -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/alidehkhodaei/data-structures-and-algorithms/HEAD/gradle/wrapper/gradle-wrapper.jar -------------------------------------------------------------------------------- /gradle/wrapper/gradle-wrapper.properties: -------------------------------------------------------------------------------- 1 | distributionBase=GRADLE_USER_HOME 2 | distributionPath=wrapper/dists 3 | distributionUrl=https\://services.gradle.org/distributions/gradle-7.3.3-bin.zip 4 | zipStoreBase=GRADLE_USER_HOME 5 | zipStorePath=wrapper/dists -------------------------------------------------------------------------------- /src/main/kotlin/array/ArrayLeftRotate.kt: -------------------------------------------------------------------------------- 1 | package array 2 | 3 | /** 4 | * Rotates an array to the left by one position. 5 | * If the array is empty, the function returns immediately without making any modifications. 6 | * 7 | * @param array The array to rotate. 8 | */ 9 | fun rotateArrayLeftByOne(array: Array) { 10 | if (array.isEmpty()) return 11 | val temp = array[0] 12 | for (i in 0 until array.size - 1) { 13 | array[i] = array[i + 1] 14 | } 15 | array[array.size - 1] = temp 16 | } -------------------------------------------------------------------------------- /src/main/kotlin/array/ArrayRightRotate.kt: -------------------------------------------------------------------------------- 1 | package array 2 | 3 | /** 4 | * Rotates an array to the right by one position. 5 | * If the array is empty, the function returns immediately without making any modifications. 6 | * 7 | * @param array The array to rotate. 8 | */ 9 | fun rotateArrayRightByOne(array: Array) { 10 | if (array.isEmpty()) return 11 | val temp = array[array.size - 1] 12 | for (i in array.size - 1 downTo 1) { 13 | array[i] = array[i - 1] 14 | } 15 | array[0] = temp 16 | } -------------------------------------------------------------------------------- /src/main/kotlin/string/StringReverse.kt: -------------------------------------------------------------------------------- 1 | package string 2 | 3 | /** 4 | * The function takes a string as input and returns the reversed version of the string. 5 | * @param str The input string that needs to be reversed. 6 | * @return the function `reverseString` returns a reversed version of the input string `str`. 7 | */ 8 | fun reverseString(str: String): String { 9 | val minimumLengthStringForReversal = 2 10 | if (str.length < minimumLengthStringForReversal) return str 11 | val stringBuilder = StringBuilder() 12 | for (i in str.length - 1 downTo 0) { 13 | stringBuilder.append(str[i]) 14 | } 15 | return stringBuilder.toString() 16 | } 17 | 18 | -------------------------------------------------------------------------------- /src/main/kotlin/array/ArrayMinMax.kt: -------------------------------------------------------------------------------- 1 | package array 2 | 3 | /** 4 | * The function finds the minimum and maximum values in an array of integers and returns them as a pair. 5 | * 6 | * @param array An array of integers. 7 | * @return The function `findMinMaxFromArray` is returning a `Pair` which contains the minimum and maximum values 8 | * in the input array. 9 | */ 10 | fun findMinMaxFromArray(array:Array):Pair { 11 | var min = array[0] 12 | var max = array[0] 13 | for (i in 1 until array.size) { 14 | if (array[i] < min) { 15 | min = array[i] 16 | } 17 | if (array[i] > max) { 18 | max = array[i] 19 | } 20 | } 21 | return Pair(min,max) 22 | } -------------------------------------------------------------------------------- /src/test/kotlin/string/StringReverseTest.kt: -------------------------------------------------------------------------------- 1 | package string 2 | 3 | import org.junit.jupiter.params.ParameterizedTest 4 | import org.junit.jupiter.params.provider.CsvSource 5 | import kotlin.test.assertEquals 6 | 7 | /** 8 | * The StringReverseTest class contains test cases for the reverseString 9 | * function, which tests the ability to reverse a given string. 10 | */ 11 | class StringReverseTest { 12 | 13 | @ParameterizedTest 14 | @CsvSource( 15 | "Kotlin, niltoK", 16 | "a, a", 17 | "Kotlin is awesome, emosewa si niltoK", 18 | "'', ''" 19 | ) 20 | fun `test reverseString function`(input: String, expected: String) { 21 | val actual = reverseString(input) 22 | assertEquals(expected, actual) 23 | } 24 | 25 | } -------------------------------------------------------------------------------- /.github/workflows/gradle-ci.yml: -------------------------------------------------------------------------------- 1 | # This workflow will build a Kotlin project with Gradle 2 | 3 | name: Build Kotlin Project 4 | 5 | on: 6 | pull_request: 7 | branches: 8 | - '**' # matches every branch 9 | push: 10 | branches: 11 | - '**' # matches every branch 12 | 13 | jobs: 14 | build: 15 | runs-on: ubuntu-20.04 16 | steps: 17 | 18 | - name: Checkout repository 19 | uses: actions/checkout@v3 20 | 21 | - name: Set up JDK 17 22 | uses: actions/setup-java@v3 23 | with: 24 | java-version: '17' 25 | distribution: 'temurin' 26 | 27 | - name: Setup Gradle 28 | uses: gradle/gradle-build-action@v2.7.1 29 | with: 30 | gradle-version: 7.4.2 31 | 32 | - name: Grant execute permission for gradlew 33 | run: chmod +x gradlew 34 | 35 | - name: Build and run 36 | run: ./gradlew build -------------------------------------------------------------------------------- /src/main/kotlin/trie/README.md: -------------------------------------------------------------------------------- 1 | # Trie 2 | Trie 3 | 4 | | Problem | Solution | 5 | |-------------| --------- | 6 | | Construct a trie from scratch | | 7 | | Find shortest unique prefix for every word in a given list | | 8 | | Word Break Problem | (Trie solution) | | 9 | | Given a sequence of words, print all anagrams together | | 10 | | Implement a Phone Directory | | 11 | | Print unique rows in a given boolean matrix | | 12 | -------------------------------------------------------------------------------- /src/main/kotlin/array/ArrayReverse.kt: -------------------------------------------------------------------------------- 1 | package array 2 | 3 | /** 4 | * The function then reverses the elements of the array between the starting and ending indices using a while loop 5 | * and a temporary variable `temp`. Finally, the function returns the reversed array. 6 | * @param array a array 7 | * @param start start index array 8 | * @param end end index array 9 | * @throws IllegalArgumentException if the [start] index is greater than the [end] index 10 | * @return reverses elements in the array. 11 | **/ 12 | fun reverseArray(array: Array, start: Int, end: Int): Array { 13 | val minimumSizeArrayForReversal = 2 14 | if (start == end || array.size < minimumSizeArrayForReversal) return array 15 | if (start > end) throw IllegalArgumentException("The start should not be bigger than the end!") 16 | var index = start 17 | var lastIndex = end 18 | while (index < lastIndex) { 19 | val temp = array[index] 20 | array[index] = array[lastIndex] 21 | array[lastIndex] = temp 22 | index++ 23 | lastIndex-- 24 | } 25 | return array 26 | } 27 | -------------------------------------------------------------------------------- /licence: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Ali Dehkhodaei 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 | -------------------------------------------------------------------------------- /src/test/kotlin/array/ArrayMinMaxTest.kt: -------------------------------------------------------------------------------- 1 | package array 2 | 3 | import org.junit.jupiter.api.Assertions.assertEquals 4 | import org.junit.jupiter.params.ParameterizedTest 5 | import org.junit.jupiter.params.provider.Arguments 6 | import org.junit.jupiter.params.provider.MethodSource 7 | import java.util.stream.Stream 8 | 9 | /** 10 | * The ArrayReverseTest class contains test cases for find min and max value in an array. 11 | */ 12 | class ArrayMinMaxTest { 13 | 14 | @ParameterizedTest 15 | @MethodSource("provideTestCases") 16 | fun `test findMinMaxFromArray function`(array: Array, expectedMaxMinValue: Pair) { 17 | assertEquals(expectedMaxMinValue, findMinMaxFromArray(array)) 18 | } 19 | 20 | companion object { 21 | @JvmStatic 22 | private fun provideTestCases(): Stream { 23 | return Stream.of( 24 | Arguments.of(arrayOf(1, 2, 3), Pair(1, 3)), 25 | Arguments.of(arrayOf(1, 2, 3, 4, 3, 2, 1), Pair(1, 4)), 26 | Arguments.of(arrayOf(9, 6, 4, 3, 1, 1, 6, 0, 2, 12, 1, 7), Pair(0, 12)), 27 | ) 28 | } 29 | } 30 | 31 | } -------------------------------------------------------------------------------- /src/test/kotlin/array/ArrayLeftRotateTest.kt: -------------------------------------------------------------------------------- 1 | package array 2 | 3 | import org.junit.jupiter.api.Assertions.assertArrayEquals 4 | import org.junit.jupiter.params.ParameterizedTest 5 | import org.junit.jupiter.params.provider.Arguments 6 | import org.junit.jupiter.params.provider.MethodSource 7 | import java.util.stream.Stream 8 | 9 | /** 10 | * The ArrayRotateTest class contains test cases for the rotateArrayLeftByOne functions, 11 | * which rotate the elements of an array to the left by one position, respectively. 12 | */ 13 | class ArrayLeftRotateTest { 14 | 15 | @ParameterizedTest 16 | @MethodSource("rotateLeftProvider") 17 | fun testRotateArrayLeftByOne(input: Array, expected: Array) { 18 | rotateArrayLeftByOne(input) 19 | assertArrayEquals(expected, input) 20 | } 21 | 22 | companion object { 23 | 24 | @JvmStatic 25 | private fun rotateLeftProvider(): Stream { 26 | return Stream.of( 27 | Arguments.of(arrayOf(1, 2, 3, 4, 5), arrayOf(2, 3, 4, 5, 1)), 28 | Arguments.of(arrayOf("abc", "bcd", "cde", "def"), arrayOf("bcd", "cde", "def", "abc")), 29 | Arguments.of(arrayOf(0), arrayOf(0)) 30 | ) 31 | } 32 | 33 | } 34 | 35 | } -------------------------------------------------------------------------------- /src/test/kotlin/array/ArrayRightRotateTest.kt: -------------------------------------------------------------------------------- 1 | package array 2 | 3 | import org.junit.jupiter.api.Assertions.assertArrayEquals 4 | import org.junit.jupiter.params.ParameterizedTest 5 | import org.junit.jupiter.params.provider.Arguments 6 | import org.junit.jupiter.params.provider.MethodSource 7 | import java.util.stream.Stream 8 | 9 | /** 10 | * The ArrayRotateTest class contains test cases for the rotateArrayRightByOne functions, 11 | * which rotate the elements of an array to the right by one position, respectively. 12 | */ 13 | class ArrayRightRotateTest { 14 | 15 | @ParameterizedTest 16 | @MethodSource("rotateRightProvider") 17 | fun testRotateArrayRightByOne(input: Array, expected: Array) { 18 | rotateArrayRightByOne(input) 19 | assertArrayEquals(expected, input) 20 | } 21 | 22 | companion object { 23 | 24 | @JvmStatic 25 | private fun rotateRightProvider(): Stream { 26 | return Stream.of( 27 | Arguments.of(arrayOf(1, 2, 3, 4, 5), arrayOf(5, 1, 2, 3, 4)), 28 | Arguments.of(arrayOf("abc", "bcd", "cde", "def"), arrayOf("def", "abc", "bcd", "cde")), 29 | Arguments.of(arrayOf(0), arrayOf(0)) 30 | ) 31 | } 32 | 33 | } 34 | 35 | } -------------------------------------------------------------------------------- /src/main/kotlin/matrix/README.md: -------------------------------------------------------------------------------- 1 | # Matrix 2 | Matrix 3 | 4 | | Problem | Solution | 5 | |-------------| --------- | 6 | | Spiral traversal on a Matrix | | 7 | | Search an element in a Matrix | | 8 | | Find median in a row wise sorted matrix | | 9 | | Find row with maximum no. of 1’s | | 10 | | Print elements in sorted order using row-column wise sorted matrix | | 11 | | Maximum size rectangle | | 12 | | Find a specific pair in matrix | | 13 | | Rotate matrix by 90 degrees | | 14 | | Kth smallest element in a row-column wise sorted matrix | | 15 | | Common elements in all rows of a given matrix | | -------------------------------------------------------------------------------- /src/main/kotlin/bitmanipulation/README.md: -------------------------------------------------------------------------------- 1 | # Bit Manipulation 2 | Bit Manipulation 3 | 4 | | Problem | Solution | 5 | |-------------| --------- | 6 | | Count set bits in an integer | | 7 | | Find the two non-repeating elements in an array of repeating elements | | 8 | | Count number of bits to be flipped to convert A to B | | 9 | | Count total set bits in all numbers from 1 to n | | 10 | | Program to find whether a no is power of two | | 11 | | Find position of the only set bit | | 12 | | Copy set bits in a range | | 13 | | Divide two integers without using multiplication, division and mod operator | | 14 | | Calculate square of a number without using *, / and pow() | | 15 | | Power Set | | 16 | -------------------------------------------------------------------------------- /src/main/kotlin/heap/README.md: -------------------------------------------------------------------------------- 1 | # Heap 2 | Heap 3 | 4 | | Problem | Solution | 5 | |-------------| --------- | 6 | | Implement a Maxheap/MinHeap using arrays and recursion. | | 7 | | Sort an Array using heap. (HeapSort) | | 8 | | Maximum of all subarrays of size k. | | 9 | | “K” largest element in an array | | 10 | | Kth smallest and largest element in an unsorted array | | 11 | | Merge “K” sorted arrays. [ IMP ] | | 12 | | Merge 2 Binary Max Heaps | | 13 | | Kth largest sum continuous subarrays | | 14 | | Leetcode- reorganize strings | | 15 | | Merge “K” Sorted Linked Lists [V.IMP] | | 16 | | Smallest range in “K” Lists | | 17 | | Median in a stream of Integers | | 18 | | Check if a Binary Tree is Heap | | 19 | | Connect “n” ropes with minimum cost | | 20 | | Convert BST to Min Heap | | 21 | | Convert min heap to max heap | | 22 | | Rearrange characters in a string such that no two adjacent are same. | | 23 | | Minimum sum of two numbers formed from digits of an array | | 24 | -------------------------------------------------------------------------------- /src/main/kotlin/backtracking/README.md: -------------------------------------------------------------------------------- 1 | # Backtracking 2 | Backtracking 3 | 4 | | Problem | Solution | 5 | |-------------| --------- | 6 | | Rat in a maze Problem | | 7 | | Printing all solutions in N-Queen | | 8 | | Word Break Problem using Backtracking | | 9 | | Remove Invalid Parentheses | | 10 | | Sudoku Solver | | 11 | | M Coloring Problem | | 12 | | Print all palindromic partitions of a string | | 13 | | Subset Sum Problem | | 14 | | The Knight’s tour problem | | 15 | | Tug of War | | 16 | | Find shortest safe route in a path with landmines | | 17 | | Combinational Sum | | 18 | | Find Maximum number possible by doing at-most K swaps | | 19 | | Print all permutations of a string | | 20 | | Find if there is a path of more than k length from a source | | 21 | | Longest Possible Route in a Matrix with Hurdles | | 22 | | Print all possible paths from top left to bottom right of a mXn matrix | | 23 | | Partition of a set into K subsets with equal sum | | 24 | | Find the K-th Permutation Sequence of first N natural numbers | | 25 | -------------------------------------------------------------------------------- /gradlew.bat: -------------------------------------------------------------------------------- 1 | @rem 2 | @rem Copyright 2015 the original author or authors. 3 | @rem 4 | @rem Licensed under the Apache License, Version 2.0 (the "License"); 5 | @rem you may not use this file except in compliance with the License. 6 | @rem You may obtain a copy of the License at 7 | @rem 8 | @rem https://www.apache.org/licenses/LICENSE-2.0 9 | @rem 10 | @rem Unless required by applicable law or agreed to in writing, software 11 | @rem distributed under the License is distributed on an "AS IS" BASIS, 12 | @rem WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | @rem See the License for the specific language governing permissions and 14 | @rem limitations under the License. 15 | @rem 16 | 17 | @if "%DEBUG%" == "" @echo off 18 | @rem ########################################################################## 19 | @rem 20 | @rem Gradle startup script for Windows 21 | @rem 22 | @rem ########################################################################## 23 | 24 | @rem Set local scope for the variables with windows NT shell 25 | if "%OS%"=="Windows_NT" setlocal 26 | 27 | set DIRNAME=%~dp0 28 | if "%DIRNAME%" == "" set DIRNAME=. 29 | set APP_BASE_NAME=%~n0 30 | set APP_HOME=%DIRNAME% 31 | 32 | @rem Resolve any "." and ".." in APP_HOME to make it shorter. 33 | for %%i in ("%APP_HOME%") do set APP_HOME=%%~fi 34 | 35 | @rem Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 36 | set DEFAULT_JVM_OPTS="-Xmx64m" "-Xms64m" 37 | 38 | @rem Find java.exe 39 | if defined JAVA_HOME goto findJavaFromJavaHome 40 | 41 | set JAVA_EXE=java.exe 42 | %JAVA_EXE% -version >NUL 2>&1 43 | if "%ERRORLEVEL%" == "0" goto execute 44 | 45 | echo. 46 | echo ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 47 | echo. 48 | echo Please set the JAVA_HOME variable in your environment to match the 49 | echo location of your Java installation. 50 | 51 | goto fail 52 | 53 | :findJavaFromJavaHome 54 | set JAVA_HOME=%JAVA_HOME:"=% 55 | set JAVA_EXE=%JAVA_HOME%/bin/java.exe 56 | 57 | if exist "%JAVA_EXE%" goto execute 58 | 59 | echo. 60 | echo ERROR: JAVA_HOME is set to an invalid directory: %JAVA_HOME% 61 | echo. 62 | echo Please set the JAVA_HOME variable in your environment to match the 63 | echo location of your Java installation. 64 | 65 | goto fail 66 | 67 | :execute 68 | @rem Setup the command line 69 | 70 | set CLASSPATH=%APP_HOME%\gradle\wrapper\gradle-wrapper.jar 71 | 72 | 73 | @rem Execute Gradle 74 | "%JAVA_EXE%" %DEFAULT_JVM_OPTS% %JAVA_OPTS% %GRADLE_OPTS% "-Dorg.gradle.appname=%APP_BASE_NAME%" -classpath "%CLASSPATH%" org.gradle.wrapper.GradleWrapperMain %* 75 | 76 | :end 77 | @rem End local scope for the variables with windows NT shell 78 | if "%ERRORLEVEL%"=="0" goto mainEnd 79 | 80 | :fail 81 | rem Set variable GRADLE_EXIT_CONSOLE if you need the _script_ return code instead of 82 | rem the _cmd.exe /c_ return code! 83 | if not "" == "%GRADLE_EXIT_CONSOLE%" exit 1 84 | exit /b 1 85 | 86 | :mainEnd 87 | if "%OS%"=="Windows_NT" endlocal 88 | 89 | :omega 90 | -------------------------------------------------------------------------------- /src/test/kotlin/array/ArrayReverseTest.kt: -------------------------------------------------------------------------------- 1 | package array 2 | 3 | import org.junit.jupiter.api.Assertions.assertArrayEquals 4 | import org.junit.jupiter.api.Test 5 | import org.junit.jupiter.api.assertThrows 6 | 7 | /** 8 | * The ArrayReverseTest class contains test cases for the reverseArray function that reverses elements in an array. 9 | */ 10 | class ArrayReverseTest { 11 | 12 | @Test 13 | fun `reverseArray should correctly reverse the entire array`() { 14 | val arr = arrayOf(1, 2, 3, 4, 5) 15 | val result = reverseArray(arr, 0, arr.size - 1) 16 | val expected = arrayOf(5, 4, 3, 2, 1) 17 | assertArrayEquals(expected, result) 18 | } 19 | 20 | @Test 21 | fun `reverseArray should correctly reverse a subset of the array`() { 22 | val arr = arrayOf("Ali", "Shabnam", "Reza", "Fatemeh") 23 | val result = reverseArray(arr, 1, 2) 24 | val expected = arrayOf("Ali", "Reza", "Shabnam", "Fatemeh") 25 | assertArrayEquals(expected, result) 26 | } 27 | 28 | @Test 29 | fun `reverseArray should correctly reverse a subset of the array with decimal values`() { 30 | val arr = arrayOf(5.5, 4.4, 3.3, 2.2, 1.1) 31 | val result = reverseArray(arr, 2, 4) 32 | val expected = arrayOf(5.5, 4.4, 1.1, 2.2, 3.3) 33 | assertArrayEquals(expected, result) 34 | } 35 | 36 | @Test 37 | fun `reverseArray should correctly handle a single element array`() { 38 | val arr = arrayOf(1) 39 | val result = reverseArray(arr, 0, arr.size - 1) 40 | val expected = arrayOf(1) 41 | assertArrayEquals(expected, result) 42 | } 43 | 44 | @Test 45 | fun `reverseArray should correctly handle an empty array`() { 46 | val arr = emptyArray() 47 | val result = reverseArray(arr, 0, arr.size - 1) 48 | val expected = emptyArray() 49 | assertArrayEquals(expected, result) 50 | } 51 | 52 | @Test 53 | fun `reverseArray when start and end are equal`() { 54 | val array = arrayOf(1, 2, 3, 4, 5) 55 | val start = 2 56 | val end = 2 57 | val reversedArray = reverseArray(array, start, end) 58 | assertArrayEquals(array, reversedArray) 59 | } 60 | 61 | @Test 62 | fun `reverseArray should throw ArrayIndexOutOfBoundsException if startIndex is less than 0`() { 63 | val arr = arrayOf(1, 2, 3, 4, 5) 64 | assertThrows { reverseArray(arr, -1, 3) } 65 | } 66 | 67 | @Test 68 | fun `reverseArray should throw ArrayIndexOutOfBoundsException if endIndex is greater than the array size minus 1`() { 69 | val arr = arrayOf(1, 2, 3, 4, 5) 70 | assertThrows { reverseArray(arr, 2, 5) } 71 | } 72 | 73 | @Test 74 | fun `reverseArray should throw ArrayIndexOutOfBoundsException if startIndex is greater than endIndex`() { 75 | val arr = arrayOf(1, 2, 3, 4, 5) 76 | assertThrows { reverseArray(arr, 3, 2) } 77 | } 78 | 79 | } -------------------------------------------------------------------------------- /src/main/kotlin/binarysearchtree/README.md: -------------------------------------------------------------------------------- 1 | # Binary Search Tree 2 | Binary Search Tree 3 | 4 | | Problem | Solution | 5 | |-------------| --------- | 6 | | Find a value in a BST | | 7 | | Deletion of a node in a BST | | 8 | | Find min and max value in a BST | | 9 | | Find inorder successor and inorder predecessor in a BST | | 10 | | Check if a tree is a BST or not | | 11 | | Populate Inorder successor of all nodes | | 12 | | Find LCA  of 2 nodes in a BST | | 13 | | Construct BST from preorder traversal | | 14 | | Convert Binary tree into BST | | 15 | | Convert a normal BST into a Balanced BST | | 16 | | Merge two BST [ V.V.V>IMP ] | | 17 | | Find Kth largest element in a BST | | 18 | | Find Kth smallest element in a BST | | 19 | | Count pairs from 2 BST whose sum is equal to given value “X” | | 20 | | Find the median of BST in O(n) time and O(1) space | | 21 | | Count BST nodes that lie in a given range | | 22 | | Replace every element with the least greater element on its right | | 23 | | Given “n” appointments, find the conflicting appointments | | 24 | | Check preorder is valid or not | | 25 | | Check whether BST contains Dead end | | 26 | | Largest BST in a Binary Tree [ V.V.V.V.V IMP ] | | 27 | | Flatten BST to sorted list | | 28 | -------------------------------------------------------------------------------- /src/main/kotlin/searchingandsorting/README.md: -------------------------------------------------------------------------------- 1 | # Searching and Sorting 2 | Searching and Sorting 3 | 4 | | Problem | Solution | 5 | |-------------| --------- | 6 | | Find first and last positions of an element in a sorted array | | 7 | | Find a Fixed Point (Value equal to index) in a given array | | 8 | | Search in a rotated sorted array | | 9 | | Square root of an integer | | 10 | | Maximum and minimum of an array using minimum number of comparisons | | 11 | | Optimum location of point to minimize total distance | | 12 | | Find the repeating and the missing | | 13 | | Find majority element | | 14 | | Searching in an array where adjacent differ by at most k | | 15 | | Find a pair with a given difference | | 16 | | Find four elements that sum to a given value | | 17 | | Maximum sum such that no 2 elements are adjacent | | 18 | | Count triplet with sum smaller than a given value | | 19 | | Merge 2 sorted arrays | | 20 | | Product array Puzzle | | 21 | | Sort array according to count of set bits | | 22 | | Minimum no. of swaps required to sort the array | | 23 | | Bishu and Soldiers | | 24 | | Rasta and Kheshtak | | 25 | | Kth smallest number again | | 26 | | Find pivot element in a sorted array | | 27 | | K-th Element of Two Sorted Arrays | | 28 | | Aggressive cows | | 29 | | Book Allocation Problem | | 30 | | EKOSPOJ: | | 31 | | Job Scheduling Algo | | 32 | | Missing Number in AP | | 33 | | Smallest number with atleast n trailing zeroes in factorial | | 34 | | Painters Partition Problem | | 35 | | ROTI-Prata SPOJ | | 36 | | DoubleHelix SPOJ | | 37 | | Subset Sums | | 38 | | Find the inversion count | | 39 | | Implement Merge-sort in-place | | 40 | | Partitioning and Sorting Arrays with Many Repeated Entries | | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Data Structures and Algorithms (Dsa) 2 | 3 | Banner 4 | 5 | Arrays Matrix Strings Searching and Sorting Linked List Bit Manipulation Greedy Backtracking Dynamic Programming Stacks and Queues Binary Trees Binary Search Tree Graphs Heap Trie 6 | 7 | This repository contains the Kotlin solutions with unit tests 8 | for Data Structures and Algorithms. This 450 coding questions provided by Love Babbar. 9 | 10 | ❌ If you notice any mistakes in the questions or solutions, please open an issue and note that the existing solutions may not be the best ones. Therefore, feel free to suggest better solutions with your contribution. 11 | 12 | ## Introduction 13 | ✅ Data structures and algorithms are two essential concepts in computer science and programming. 14 | 15 | ✅ Data structures refer to the way we organize and store data in a computer program. They are used to manage and manipulate data efficiently. Some common data structures include arrays, linked lists, stacks, queues, trees, and graphs. 16 | 17 | ✅ Algorithms, on the other hand, are a set of steps or instructions that are followed to solve a problem. Algorithms can range from simple to complex, depending on the problem being solved. Some common algorithms include searching, sorting, and traversal algorithms. 18 | 19 | ✅ By choosing the right data structure and algorithm, programmers can write efficient and effective code that solves complex problems. 20 | 21 | ## Table of contents 22 | - [Arrays](https://github.com/alidehkhodaei/dsa/tree/main/src/main/kotlin/array) 23 | - [Matrix](https://github.com/alidehkhodaei/dsa/tree/main/src/main/kotlin/matrix) 24 | - [Strings](https://github.com/alidehkhodaei/dsa/tree/main/src/main/kotlin/string) 25 | - [Searching and Sorting](https://github.com/alidehkhodaei/dsa/tree/main/src/main/kotlin/searchingandsorting) 26 | - [Linked List](https://github.com/alidehkhodaei/dsa/tree/main/src/main/kotlin/linkedlist) 27 | - [Bit Manipulation](https://github.com/alidehkhodaei/dsa/tree/main/src/main/kotlin/bitmanipulation) 28 | - [Greedy](https://github.com/alidehkhodaei/dsa/tree/main/src/main/kotlin/greedy) 29 | - [Backtracking](https://github.com/alidehkhodaei/dsa/tree/main/src/main/kotlin/backtracking) 30 | - [Dynamic Programming](https://github.com/alidehkhodaei/dsa/tree/main/src/main/kotlin/dynamicprogramming) 31 | - [Stacks and Queues](https://github.com/alidehkhodaei/dsa/tree/main/src/main/kotlin/stackandqueue) 32 | - [Binary Trees](https://github.com/alidehkhodaei/dsa/tree/main/src/main/kotlin/binarytree) 33 | - [Binary Search Tree](https://github.com/alidehkhodaei/dsa/tree/main/src/main/kotlin/binarysearchtree) 34 | - [Graphs](https://github.com/alidehkhodaei/dsa/tree/main/src/main/kotlin/graph) 35 | - [Heap](https://github.com/alidehkhodaei/dsa/tree/main/src/main/kotlin/heap) 36 | - [Trie](https://github.com/alidehkhodaei/dsa/tree/main/src/main/kotlin/trie) 37 | 38 | ## Usefull resource 39 | - Geeksforgeeks 40 | - Programiz 41 | - visualising dsa through animation 42 | - Data Structure Visualizations 43 | - Learners lesson 44 | - Hackerearth 45 | - Hackerrank 46 | - Leetcode 47 | - Algorithm visualizer 48 | 49 | ## Contributing 50 | 1. Fork the repository. 51 | 2. Clone the forked repository to your local machine. 52 | 3. Create a new branch for your contribution. 53 | 4. Make changes, write unit test and documentation, commit them. 54 | 5. Push changes to your forked repository. 55 | 6. Open a pull request. 56 | 57 | ## License 58 | This repository is licensed under the [MIT License](https://choosealicense.com/licenses/mit/). 59 | 60 | -------------------------------------------------------------------------------- /src/main/kotlin/greedy/README.md: -------------------------------------------------------------------------------- 1 | # Greedy 2 | Greedy 3 | 4 | | Problem | Solution | 5 | |-------------| --------- | 6 | | Activity Selection Problem | | 7 | | Job Sequencing Problem | | 8 | | Huffman Coding | | 9 | | Water Connection Problem | | 10 | | Fractional Knapsack Problem | | 11 | | Greedy Algorithm to find Minimum number of Coins | | 12 | | Maximum trains for which stoppage can be provided | | 13 | | Minimum Platforms Problem | | 14 | | Buy Maximum Stocks if i stocks can be bought on i-th day | | 15 | | Find the minimum and maximum amount to buy all N candies | | 16 | | Minimize Cash Flow among a given set of friends who have borrowed money from each other | | 17 | | Minimum Cost to cut a board into squares | | 18 | | Check if it is possible to survive on Island | | 19 | | Find maximum meetings in one room | | 20 | | Maximum product subset of an array | | 21 | | Maximize array sum after K negations | | 22 | | Maximize the sum of arr[i]*i | | 23 | | Maximum sum of absolute difference of an array | | 24 | | Maximize sum of consecutive differences in a circular array | | 25 | | Minimum sum of absolute difference of pairs of two arrays | | 26 | | Program for Shortest Job First (or SJF) CPU Scheduling | | 27 | | Program for Least Recently Used (LRU) Page Replacement algorithm | | 28 | | Smallest subset with sum greater than all other elements | | 29 | | Chocolate Distribution Problem | | 30 | | DEFKIN -Defense of a Kingdom | | 31 | | DIEHARD -DIE HARD | | 32 | | GERGOVIA -Wine trading in Gergovia | | 33 | | Picking Up Chicks | | 34 | | CHOCOLA –Chocolate | | 35 | | ARRANGE -Arranging Amplifiers | | 36 | | K Centers Problem | | 37 | | Minimum Cost of ropes | | 38 | | Find smallest number with given number of digits and sum of digits | | 39 | | Rearrange characters in a string such that no two adjacent are same | | 40 | | Find maximum sum possible equal sum of three stacks | | 41 | -------------------------------------------------------------------------------- /src/main/kotlin/linkedlist/README.md: -------------------------------------------------------------------------------- 1 | # Linked List 2 | Linked List 3 | 4 | | Problem | Solution | 5 | |-------------| --------- | 6 | | Write a Program to reverse the Linked List. (Both Iterative and recursive) | | 7 | | Reverse a Linked List in group of Given Size. [Very Imp] | | 8 | | Write a program to Detect loop in a linked list. | | 9 | | Write a program to Delete loop in a linked list. | | 10 | | Find the starting point of the loop. | | 11 | | Remove Duplicates in a sorted Linked List. | | 12 | | Remove Duplicates in a Un-sorted Linked List. | | 13 | | Write a Program to Move the last element to Front in a Linked List. | | 14 | | Add “1” to a number represented as a Linked List. | | 15 | | Add two numbers represented by linked lists. | | 16 | | Intersection of two Sorted Linked List. | | 17 | | Intersection Point of two Linked Lists. | | 18 | | Merge Sort For Linked lists.[Very Important] | | 19 | | Quicksort for Linked Lists.[Very Important] | | 20 | | Find the middle Element of a linked list. | | 21 | | Check if a linked list is a circular linked list. | | 22 | | Split a Circular linked list into two halves. | | 23 | | Write a Program to check whether the Singly Linked list is a palindrome or not. | | 24 | | Deletion from a Circular Linked List. | | 25 | | Reverse a Doubly Linked list. | | 26 | | Find pairs with a given sum in a DLL. | | 27 | | Count triplets in a sorted DLL whose sum is equal to given value “X”. | | 28 | | Sort a “k”sorted Doubly Linked list.[Very IMP] | | 29 | | Rotate Doubly Linked list by N nodes. | | 30 | | Rotate a Doubly Linked list in group of Given Size.[Very IMP] | | 31 | | Can we reverse a linked list in less than O(n)? | | 32 | | Why Quicksort is preferred for. Arrays and Merge Sort for Linked Lists? | | 33 | | Flatten a Linked List | | 34 | | Sort a LL of 0’s, 1’s and 2’s | | 35 | | Clone a linked list with next and random pointer | | 36 | | Merge K sorted Linked list | | 37 | | Multiply 2 no. represented by LL | | 38 | | Delete nodes which have a greater value on right side | | 39 | | Segregate even and odd nodes in a Linked List | | 40 | | Program for n’th node from the end of a Linked List | | -------------------------------------------------------------------------------- /src/main/kotlin/binarytree/README.md: -------------------------------------------------------------------------------- 1 | # Binary Trees 2 | Binary Trees 3 | 4 | | Problem | Solution | 5 | |-------------| --------- | 6 | | Level order traversal | | 7 | | Reverse Level Order traversal | | 8 | | Height of a tree | | 9 | | Diameter of a tree | | 10 | | Mirror of a tree | | 11 | | Inorder Traversal of a tree both using recursion and Iteration | | 12 | | Preorder Traversal of a tree both using recursion and Iteration | | 13 | | Postorder Traversal of a tree both using recursion and Iteration | | 14 | | Left View of a tree | | 15 | | Right View of Tree | | 16 | | Top View of a tree | | 17 | | Bottom View of a tree | | 18 | | Zig-Zag traversal of a binary tree | | 19 | | Check if a tree is balanced or not | | 20 | | Diagonal Traversal of a Binary tree | | 21 | | Boundary traversal of a Binary tree | | 22 | | Construct Binary Tree from String with Bracket Representation | | 23 | | Convert Binary tree into Doubly Linked List | | 24 | | Convert Binary tree into Sum tree | | 25 | | Construct Binary tree from Inorder and preorder traversal | | 26 | | Find minimum swaps required to convert a Binary tree into BST | | 27 | | Check if Binary tree is Sum tree or not | | 28 | | Check if all leaf nodes are at same level or not | | 29 | | Check if a Binary Tree contains duplicate subtrees of size 2 or more [ IMP ] | | 30 | | Check if 2 trees are mirror or not | | 31 | | Sum of Nodes on the Longest path from root to leaf node | | 32 | | Check if given graph is tree or not.  [ IMP ] | | 33 | | Find Largest subtree sum in a tree | | 34 | | Maximum Sum of nodes in Binary tree such that no two are adjacent | | 35 | | Print all “K” Sum paths in a Binary tree | | 36 | | Find LCA in a Binary tree | | 37 | | Find distance between 2 nodes in a Binary tree | | 38 | | Kth Ancestor of node in a Binary tree | | 39 | | Find all Duplicate subtrees in a Binary tree [ IMP ] | | 40 | | Tree Isomorphism Problem | | 41 | -------------------------------------------------------------------------------- /src/main/kotlin/stackandqueue/README.md: -------------------------------------------------------------------------------- 1 | # Stacks and Queues 2 | Stacks and Queues 3 | 4 | | Problem | Solution | 5 | |-------------| --------- | 6 | | Implement Stack from Scratch | | 7 | | Implement Queue from Scratch | | 8 | | Implement 2 stack in an array | | 9 | | Find the middle element of a stack | | 10 | | Implement “N” stacks in an Array | | 11 | | Check the expression has valid or Balanced parenthesis or not. | | 12 | | Reverse a String using Stack | | 13 | | Design a Stack that supports getMin() in O(1) time and O(1) extra space. | | 14 | | Find the next Greater element | | 15 | | The celebrity Problem | | 16 | | Arithmetic Expression evaluation | | 17 | | Evaluation of Postfix expression | | 18 | | Implement a method to insert an element at its bottom without using any other data structure. | | 19 | | Reverse a stack using recursion | | 20 | | Sort a Stack using recursion | | 21 | | Merge Overlapping Intervals | | 22 | | Largest rectangular Area in Histogram | | 23 | | Length of the Longest Valid Substring | | 24 | | Expression contains redundant bracket or not | | 25 | | Implement Stack using Queue | | 26 | | Implement Stack using Deque | | 27 | | Stack Permutations (Check if an array is stack permutation of other) | | 28 | | Implement Queue using Stack | | 29 | | Implement “n” queue in an array | | 30 | | Implement a Circular queue | | 31 | | LRU Cache Implementation | | 32 | | Reverse a Queue using recursion | | 33 | | Reverse the first “K” elements of a queue | | 34 | | Interleave the first half of the queue with second half | | 35 | | Find the first circular tour that visits all Petrol Pumps | | 36 | | Minimum time required to rot all oranges | | 37 | | Distance of nearest cell having 1 in a binary matrix | | 38 | | First negative integer in every window of size “k” | | 39 | | Check if all levels of two trees are anagrams or not. | | 40 | | Sum of minimum and maximum elements of all subarrays of size “k”. | | 41 | | Minimum sum of squares of character counts in a given string after removing “k” characters. | | 42 | | Queue based approach or first non-repeating character in a stream. | | 43 | | Next Smaller Element | | -------------------------------------------------------------------------------- /src/main/kotlin/graph/README.md: -------------------------------------------------------------------------------- 1 | # Graphs 2 | Graphs 3 | 4 | | Problem | Solution | 5 | |-------------| --------- | 6 | | Create a Graph, print it | | 7 | | Implement BFS algorithm | | 8 | | Implement DFS Algo | | 9 | | Detect Cycle in Directed Graph using BFS/DFS Algo | | 10 | | Detect Cycle in UnDirected Graph using BFS/DFS Algo | | 11 | | Search in a Maze | | 12 | | Minimum Step by Knight | | 13 | | Flood fill algo | | 14 | | Clone a graph | | 15 | | Making wired Connections | | 16 | | Word Ladder | | 17 | | Dijkstra algo | | 18 | | Implement Topological Sort | | 19 | | Minimum time taken by each job to be completed given by a Directed Acyclic Graph | | 20 | | Find whether it is possible to finish all tasks or not from given dependencies | | 21 | | Find the no. of Islands | | 22 | | Given a sorted Dictionary of an Alien Language, find order of characters | | 23 | | Implement Kruksal’sAlgorithm | | 24 | | Implement Prim’s Algorithm | | 25 | | Total no. of Spanning tree in a graph | | 26 | | Implement Bellman Ford Algorithm | | 27 | | Implement Floyd warshall Algorithm | | 28 | | Travelling Salesman Problem | | 29 | | Graph Colouring Problem | | 30 | | Snake and Ladders Problem | | 31 | | Find bridge in a graph | | 32 | | Count Strongly connected Components(Kosaraju Algo) | | 33 | | Check whether a graph is Bipartite or Not | | 34 | | Detect Negative cycle in a graph | | 35 | | Longest path in a Directed Acyclic Graph | | 36 | | Journey to the Moon | | 37 | | Cheapest Flights Within K Stops | | 38 | | Oliver and the Game | | 39 | | Water Jug problem using BFS | | 40 | | Find if there is a path of more thank length from a source | | 41 | | M-Colouring Problem | | 42 | | Minimum edges to reverse to make path from source to destination | | 43 | | Paths to travel each nodes using each edge(Seven Bridges) | | 44 | | Vertex Cover Problem | | 45 | | Chinese Postman or Route Inspection | | 46 | | Number of Triangles in a Directed and Undirected Graph | | 47 | | Minimise the cashflow among a given set of friends who have borrowed money from each other | | 48 | | Two Clique Problem | | 49 | -------------------------------------------------------------------------------- /src/main/kotlin/dynamicprogramming/README.md: -------------------------------------------------------------------------------- 1 | # Dynamic Programming 2 | Dynamic Programming 3 | 4 | | Problem | Solution | 5 | |-------------| --------- | 6 | | Coin Change Problem | | 7 | | Knapsack Problem | | 8 | | Binomial Coefficient Problem | | 9 | | Permutation Coefficient Problem | | 10 | | Program for nth Catalan Number | | 11 | | Matrix Chain Multiplication | | 12 | | Edit Distance | | 13 | | Subset Sum Problem | | 14 | | Friends Pairing Problem | | 15 | | Gold Mine Problem | | 16 | | Assembly Line Scheduling Problem | | 17 | | Painting the Fence problem | | 18 | | Maximize The Cut Segments | | 19 | | Longest Common Subsequence | | 20 | | Longest Repeated Subsequence | | 21 | | Longest Increasing Subsequence | | 22 | | Space Optimized Solution of LCS | | 23 | | LCS (Longest Common Subsequence) of three strings | | 24 | | Maximum Sum Increasing Subsequence | | 25 | | Count all subsequences having product less than K | | 26 | | Longest subsequence such that difference between adjacent is one | | 27 | | Maximum subsequence sum such that no three are consecutive | | 28 | | Egg Dropping Problem | | 29 | | Maximum Length Chain of Pairs | | 30 | | Maximum size square sub-matrix with all 1s | | 31 | | Maximum sum of pairs with specific difference | | 32 | | Min Cost Path Problem | | 33 | | Maximum difference of zeros and ones in binary string | | 34 | | Minimum number of jumps to reach end | | 35 | | Minimum cost to fill given weight in a bag | | 36 | | Minimum removals from array to make max –min <= K | | 37 | | Longest Common Substring | | 38 | | Count number of ways to reach a given score in a game | | 39 | | Count Balanced Binary Trees of Height h | | 40 | | LargestSum Contiguous Subarray [V>V>V>V IMP ] | | 41 | | Smallest sum contiguous subarray | | 42 | | Unbounded Knapsack (Repetition of items allowed) | | 43 | | Word Break Problem | | 44 | | Largest Independent Set Problem | | 45 | | Partition problem | | 46 | | Longest Palindromic Subsequence | | 47 | | Count All Palindromic Subsequence in a given String | | 48 | | Longest Palindromic Substring | | 49 | | Longest alternating subsequence | | 50 | | Weighted Job Scheduling | | 51 | | Coin game winner where every player has three choices | | 52 | | Count Derangements (Permutation such that no element appears in its original position) [ IMPORTANT ] | | 53 | | Maximum profit by buying and selling a share at most twice [ IMP ] | | 54 | | Optimal Strategy for a Game | | 55 | | Optimal Binary Search Tree | | 56 | | Palindrome Partitioning Problem | | 57 | | Word Wrap Problem | | 58 | | Mobile Numeric Keypad Problem [ IMP ] | | 59 | | Boolean Parenthesization Problem | | 60 | | Largest rectangular sub-matrix whose sum is 0 | | 61 | | Largest area rectangular sub-matrix with equal number of 1’s and 0’s [ IMP ] | | 62 | | Maximum sum rectangle in a 2D matrix | | 63 | | Maximum profit by buying and selling a share at most k times | | 64 | | Find if a string is interleaved of two other strings | | 65 | | Maximum Length of Pair Chain | | 66 | -------------------------------------------------------------------------------- /gradlew: -------------------------------------------------------------------------------- 1 | #!/bin/sh 2 | 3 | # 4 | # Copyright © 2015-2021 the original authors. 5 | # 6 | # Licensed under the Apache License, Version 2.0 (the "License"); 7 | # you may not use this file except in compliance with the License. 8 | # You may obtain a copy of the License at 9 | # 10 | # https://www.apache.org/licenses/LICENSE-2.0 11 | # 12 | # Unless required by applicable law or agreed to in writing, software 13 | # distributed under the License is distributed on an "AS IS" BASIS, 14 | # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | # See the License for the specific language governing permissions and 16 | # limitations under the License. 17 | # 18 | 19 | ############################################################################## 20 | # 21 | # Gradle start up script for POSIX generated by Gradle. 22 | # 23 | # Important for running: 24 | # 25 | # (1) You need a POSIX-compliant shell to run this script. If your /bin/sh is 26 | # noncompliant, but you have some other compliant shell such as ksh or 27 | # bash, then to run this script, type that shell name before the whole 28 | # command line, like: 29 | # 30 | # ksh Gradle 31 | # 32 | # Busybox and similar reduced shells will NOT work, because this script 33 | # requires all of these POSIX shell features: 34 | # * functions; 35 | # * expansions «$var», «${var}», «${var:-default}», «${var+SET}», 36 | # «${var#prefix}», «${var%suffix}», and «$( cmd )»; 37 | # * compound commands having a testable exit status, especially «case»; 38 | # * various built-in commands including «command», «set», and «ulimit». 39 | # 40 | # Important for patching: 41 | # 42 | # (2) This script targets any POSIX shell, so it avoids extensions provided 43 | # by Bash, Ksh, etc; in particular arrays are avoided. 44 | # 45 | # The "traditional" practice of packing multiple parameters into a 46 | # space-separated string is a well documented source of bugs and security 47 | # problems, so this is (mostly) avoided, by progressively accumulating 48 | # options in "$@", and eventually passing that to Java. 49 | # 50 | # Where the inherited environment variables (DEFAULT_JVM_OPTS, JAVA_OPTS, 51 | # and GRADLE_OPTS) rely on word-splitting, this is performed explicitly; 52 | # see the in-line comments for details. 53 | # 54 | # There are tweaks for specific operating systems such as AIX, CygWin, 55 | # Darwin, MinGW, and NonStop. 56 | # 57 | # (3) This script is generated from the Groovy template 58 | # https://github.com/gradle/gradle/blob/master/subprojects/plugins/src/main/resources/org/gradle/api/internal/plugins/unixStartScript.txt 59 | # within the Gradle project. 60 | # 61 | # You can find Gradle at https://github.com/gradle/gradle/. 62 | # 63 | ############################################################################## 64 | 65 | # Attempt to set APP_HOME 66 | 67 | # Resolve links: $0 may be a link 68 | app_path=$0 69 | 70 | # Need this for daisy-chained symlinks. 71 | while 72 | APP_HOME=${app_path%"${app_path##*/}"} # leaves a trailing /; empty if no leading path 73 | [ -h "$app_path" ] 74 | do 75 | ls=$( ls -ld "$app_path" ) 76 | link=${ls#*' -> '} 77 | case $link in #( 78 | /*) app_path=$link ;; #( 79 | *) app_path=$APP_HOME$link ;; 80 | esac 81 | done 82 | 83 | APP_HOME=$( cd "${APP_HOME:-./}" && pwd -P ) || exit 84 | 85 | APP_NAME="Gradle" 86 | APP_BASE_NAME=${0##*/} 87 | 88 | # Add default JVM options here. You can also use JAVA_OPTS and GRADLE_OPTS to pass JVM options to this script. 89 | DEFAULT_JVM_OPTS='"-Xmx64m" "-Xms64m"' 90 | 91 | # Use the maximum available, or set MAX_FD != -1 to use that value. 92 | MAX_FD=maximum 93 | 94 | warn () { 95 | echo "$*" 96 | } >&2 97 | 98 | die () { 99 | echo 100 | echo "$*" 101 | echo 102 | exit 1 103 | } >&2 104 | 105 | # OS specific support (must be 'true' or 'false'). 106 | cygwin=false 107 | msys=false 108 | darwin=false 109 | nonstop=false 110 | case "$( uname )" in #( 111 | CYGWIN* ) cygwin=true ;; #( 112 | Darwin* ) darwin=true ;; #( 113 | MSYS* | MINGW* ) msys=true ;; #( 114 | NONSTOP* ) nonstop=true ;; 115 | esac 116 | 117 | CLASSPATH=$APP_HOME/gradle/wrapper/gradle-wrapper.jar 118 | 119 | 120 | # Determine the Java command to use to start the JVM. 121 | if [ -n "$JAVA_HOME" ] ; then 122 | if [ -x "$JAVA_HOME/jre/sh/java" ] ; then 123 | # IBM's JDK on AIX uses strange locations for the executables 124 | JAVACMD=$JAVA_HOME/jre/sh/java 125 | else 126 | JAVACMD=$JAVA_HOME/bin/java 127 | fi 128 | if [ ! -x "$JAVACMD" ] ; then 129 | die "ERROR: JAVA_HOME is set to an invalid directory: $JAVA_HOME 130 | 131 | Please set the JAVA_HOME variable in your environment to match the 132 | location of your Java installation." 133 | fi 134 | else 135 | JAVACMD=java 136 | which java >/dev/null 2>&1 || die "ERROR: JAVA_HOME is not set and no 'java' command could be found in your PATH. 137 | 138 | Please set the JAVA_HOME variable in your environment to match the 139 | location of your Java installation." 140 | fi 141 | 142 | # Increase the maximum file descriptors if we can. 143 | if ! "$cygwin" && ! "$darwin" && ! "$nonstop" ; then 144 | case $MAX_FD in #( 145 | max*) 146 | MAX_FD=$( ulimit -H -n ) || 147 | warn "Could not query maximum file descriptor limit" 148 | esac 149 | case $MAX_FD in #( 150 | '' | soft) :;; #( 151 | *) 152 | ulimit -n "$MAX_FD" || 153 | warn "Could not set maximum file descriptor limit to $MAX_FD" 154 | esac 155 | fi 156 | 157 | # Collect all arguments for the java command, stacking in reverse order: 158 | # * args from the command line 159 | # * the main class name 160 | # * -classpath 161 | # * -D...appname settings 162 | # * --module-path (only if needed) 163 | # * DEFAULT_JVM_OPTS, JAVA_OPTS, and GRADLE_OPTS environment variables. 164 | 165 | # For Cygwin or MSYS, switch paths to Windows format before running java 166 | if "$cygwin" || "$msys" ; then 167 | APP_HOME=$( cygpath --path --mixed "$APP_HOME" ) 168 | CLASSPATH=$( cygpath --path --mixed "$CLASSPATH" ) 169 | 170 | JAVACMD=$( cygpath --unix "$JAVACMD" ) 171 | 172 | # Now convert the arguments - kludge to limit ourselves to /bin/sh 173 | for arg do 174 | if 175 | case $arg in #( 176 | -*) false ;; # don't mess with options #( 177 | /?*) t=${arg#/} t=/${t%%/*} # looks like a POSIX filepath 178 | [ -e "$t" ] ;; #( 179 | *) false ;; 180 | esac 181 | then 182 | arg=$( cygpath --path --ignore --mixed "$arg" ) 183 | fi 184 | # Roll the args list around exactly as many times as the number of 185 | # args, so each arg winds up back in the position where it started, but 186 | # possibly modified. 187 | # 188 | # NB: a `for` loop captures its iteration list before it begins, so 189 | # changing the positional parameters here affects neither the number of 190 | # iterations, nor the values presented in `arg`. 191 | shift # remove old arg 192 | set -- "$@" "$arg" # push replacement arg 193 | done 194 | fi 195 | 196 | # Collect all arguments for the java command; 197 | # * $DEFAULT_JVM_OPTS, $JAVA_OPTS, and $GRADLE_OPTS can contain fragments of 198 | # shell script including quotes and variable substitutions, so put them in 199 | # double quotes to make sure that they get re-expanded; and 200 | # * put everything else in single quotes, so that it's not re-expanded. 201 | 202 | set -- \ 203 | "-Dorg.gradle.appname=$APP_BASE_NAME" \ 204 | -classpath "$CLASSPATH" \ 205 | org.gradle.wrapper.GradleWrapperMain \ 206 | "$@" 207 | 208 | # Use "xargs" to parse quoted args. 209 | # 210 | # With -n1 it outputs one arg per line, with the quotes and backslashes removed. 211 | # 212 | # In Bash we could simply go: 213 | # 214 | # readarray ARGS < <( xargs -n1 <<<"$var" ) && 215 | # set -- "${ARGS[@]}" "$@" 216 | # 217 | # but POSIX shell has neither arrays nor command substitution, so instead we 218 | # post-process each arg (as a line of input to sed) to backslash-escape any 219 | # character that might be a shell metacharacter, then use eval to reverse 220 | # that process (while maintaining the separation between arguments), and wrap 221 | # the whole thing up as a single "set" statement. 222 | # 223 | # This will of course break if any of these variables contains a newline or 224 | # an unmatched quote. 225 | # 226 | 227 | eval "set -- $( 228 | printf '%s\n' "$DEFAULT_JVM_OPTS $JAVA_OPTS $GRADLE_OPTS" | 229 | xargs -n1 | 230 | sed ' s~[^-[:alnum:]+,./:=@_]~\\&~g; ' | 231 | tr '\n' ' ' 232 | )" '"$@"' 233 | 234 | exec "$JAVACMD" "$@" 235 | -------------------------------------------------------------------------------- /src/main/kotlin/array/README.md: -------------------------------------------------------------------------------- 1 | # Arrays 2 | Arrays 3 | 4 | | Problem | Solution | 5 | |-------------|----------------------------------------------------------------------------------------------------------------------------------------| 6 | | Reverse the array | Link | 7 | | Find the maximum and minimum element in an array | Link | 8 | | Find the “Kth” max and min element of an array | | 9 | | Given an array which consists of only 0, 1 and 2. Sort the array without using any sorting algo | | 10 | | Move all the negative elements to one side of the array | | 11 | | Find the Union and Intersection of the two sorted arrays. | | 12 | | Rotates an array to the right by one position. | Link | 13 | | Rotates an array to the left by one position. | Link | 14 | | Find Largest sum contiguous Subarray [V. IMP] | | 15 | | Minimize the maximum difference between heights [V.IMP] | | 16 | | Minimum no. of Jumps to reach end of an array | | 17 | | Find duplicate in an array of N+1 Integers | | 18 | | Merge 2 sorted arrays without using Extra space. | | 19 | | Kadane’s Algo [V.V.V.V.V IMP] | | 20 | | Merge Intervals | | 21 | | Next Permutation | | 22 | | Count Inversion | | 23 | | Best time to buy and Sell stock | | 24 | | Find all pairs on integer array whose sum is equal to given number | | 25 | | Find common elements In 3 sorted arrays | | 26 | | Rearrange the array in alternating positive and negative items with O(1) extra space | | 27 | | Find if there is any subarray with sum equal to 0 | | 28 | | Find factorial of a large number | | 29 | | Find maximum product subarray | | 30 | | Find longest consecutive subsequence | | 31 | | Given an array of size n and a number k, fin all elements that appear more than ” n/k ” times. | | 32 | | Maximum profit by buying and selling a share at most twice | | 33 | | Find whether an array is a subset of another array | | 34 | | Find the triplet that sum to a given value | | 35 | | Trapping Rain water problem | | 36 | | Chocolate Distribution problem | | 37 | | Smallest Subarray with sum greater than a given value | | 38 | | Three way partitioning of an array around a given value | | 39 | | Minimum swaps required bring elements less equal K together | | 40 | | Minimum no. of operations required to make an array palindrome | | 41 | | Median of 2 sorted arrays of equal size | | 42 | | Median of 2 sorted arrays of different size | | 43 | 44 | -------------------------------------------------------------------------------- /src/main/kotlin/string/README.md: -------------------------------------------------------------------------------- 1 | # Strings 2 | Strings 3 | 4 | | Problem | Solution | 5 | |-------------|--------------------------------------------------------------------------------------------------------------------------------------| 6 | | Reverse a String | Link | 7 | | Check whether a String is Palindrome or not | | 8 | | Find Duplicate characters in a string | | 9 | | Why strings are immutable in Java? | | 10 | | Write a Code to check whether one string is a rotation of another | | 11 | | Write a Program to check whether a string is a valid shuffle of two strings or not | | 12 | | Count and Say problem | | 13 | | Write a program to find the longest Palindrome in a string.[ Longest palindromic Substring] | | 14 | | Find Longest Recurring Subsequence in String | | 15 | | Print all Subsequences of a string | | 16 | | Print all the permutations of the given string | | 17 | | Split the Binary string into two substring with equal 0’s and 1’s | | 18 | | Word Wrap Problem [VERY IMP]. | | 19 | | EDIT Distance [Very Imp] | | 20 | | Find next greater number with same set of digits. [Very Very IMP] | | 21 | | Balanced Parenthesis problem.[Imp] | | 22 | | Word break Problem[ Very Imp] | | 23 | | Rabin Karp Algorithm | | 24 | | KMP Algorithm | | 25 | | Convert a Sentence into its equivalent mobile numeric keypad sequence. | | 26 | | Minimum number of bracket reversals needed to make an expression balanced. | | 27 | | Count All Palindromic Subsequence in a given String. | | 28 | | Count of number of given string in 2D character array | | 29 | | Search a Word in a 2D Grid of characters. | | 30 | | Boyer Moore Algorithm for Pattern Searching. | | 31 | | Converting Roman Numerals to Decimal | | 32 | | Longest Common Prefix | | 33 | | Number of flips to make binary string alternate | | 34 | | Find the first repeated word in string. | | 35 | | Minimum number of swaps for bracket balancing. | | 36 | | Find the longest common subsequence between two strings. | | 37 | | Program to generate all possible valid IP addresses from given  string. | | 38 | | Write a program to find the smallest window that contains all characters of string itself. | | 39 | | Rearrange characters in a string such that no two adjacent are same | | 40 | | Minimum characters to be added at front to make string palindrome | | 41 | | Given a sequence of words, print all anagrams together | | 42 | | Find the smallest window in a string containing all characters of another string | | 43 | | Recursively remove all adjacent duplicates | | 44 | | String matching where one string contains wildcard characters | | 45 | | Function to find Number of customers who could not get a computer | | 46 | | Transform One String to Another using Minimum Number of Given Operation | | 47 | | Check if two given strings are isomorphic to each other | | 48 | | Recursively print all sentences that can be formed from list of word lists | | 49 | --------------------------------------------------------------------------------