Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions ContiguousArray.kt
Original file line number Diff line number Diff line change
@@ -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<Int,Int>().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
}
}
25 changes: 25 additions & 0 deletions LongestPalindrome.kt
Original file line number Diff line number Diff line change
@@ -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<Char>();
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;
}
}
21 changes: 21 additions & 0 deletions SubarraySum.kt
Original file line number Diff line number Diff line change
@@ -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<Int,Int>().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
}
}