diff --git a/ContiguousArray.kt b/ContiguousArray.kt new file mode 100644 index 00000000..8d9ab1bd --- /dev/null +++ b/ContiguousArray.kt @@ -0,0 +1,27 @@ +//TimeComplexity O(n) +//SpaceComplexity O(n) +//In this problem we need to find balanced array of 0 or 1, we keep a running sum where we decrement when we observe 0 and increment when we observe 1 +// if the map already contains the running sum, it means we have found a balanced subarray. we check the max of index where we have found the subarray. + +class Solution { + fun findMaxLength(nums: IntArray): Int { + val map = mutableMapOf().apply { + put(0, -1) + } + + var max = 0 + var rSum = 0 + for (i in 0..nums.size - 1) { + val num = nums[i] + if (num == 0) rSum-- + else rSum++ + + if(map.containsKey(rSum)) { + max = Math.max(max, i - map.getOrDefault(rSum, 0)) + } else { + map.put(rSum, i) + } + } + return max + } +} \ No newline at end of file diff --git a/LongestPalindrome.kt b/LongestPalindrome.kt new file mode 100644 index 00000000..d83fd819 --- /dev/null +++ b/LongestPalindrome.kt @@ -0,0 +1,25 @@ +//TimeComplexity O(n) +//SpaceComplexity O(1) 52 charackters at the max(26 for smallcase letters and 26 for uppercase letters). +// In this problem we need provide length of longest palindrome possible. we store the characters in a hashset, +// we add an element when we come across it first time and then pop or remove it when we come across same charater again. +// When returning the count we check if there is an element left in the hashset, if true then we add 1 to the count and return the count. + +class Solution { + fun longestPalindrome(s: String): Int { + val set = HashSet(); + var count = 0; + + for(i in 0..s.lastIndex) { + if(set.contains(s[i])) { + set.remove(s[i]) + count += 2 + } else { + set.add(s[i]) + } + } + if(!set.isEmpty()) { + count++ + } + return count; + } +} \ No newline at end of file diff --git a/SubarraySum.kt b/SubarraySum.kt new file mode 100644 index 00000000..fb78d7a5 --- /dev/null +++ b/SubarraySum.kt @@ -0,0 +1,21 @@ +//Time Complexity O(n) +//Space Complexity O(n) +//In this problem we keep a running Sum and check if runningSum - k (target) has already occured in the hasmap before. If it has we increase the count and return the number of subarrays. +class Solution { + fun subarraySum(nums: IntArray, k: Int): Int { + + val prefixSum = mutableMapOf().apply { + put(0, 1) + } + + var count = 0 + var runningSum = 0 + + for(n in nums) { + runningSum = runningSum + n + count += prefixSum.getOrDefault(runningSum - k, 0) + prefixSum.put(runningSum, prefixSum.getOrDefault(runningSum, 0) + 1) + } + return count + } +} \ No newline at end of file