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
25 changes: 25 additions & 0 deletions DeleteDuplicateElements.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
//In this probllem, we are using two pointer technique. We have a slow pointer which keeps track of the position to write the next non duplicate element.
// We also maintain a count variable to keep track of the number of occurrences of the current element. If the count is less than or equal to 2, we write the element at the slow pointer and increment the slow pointer.
//Time Complexity: O(n)
//Space Complexity: O(1)

class Solution {
fun removeDuplicates(nums: IntArray): Int {
var slow = 1
var count = 1

for(i in 1..nums.size -1) {
if(nums[i] == nums[i-1]) {
count++
} else {
count = 1
}

if (count <= 2) {
nums[slow] = nums[i]
slow++
}
}
return slow
}
}
30 changes: 30 additions & 0 deletions MergeSortedArray.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
// In this problem, we have kept two pointers, one for each array pointing to the end of the valid elements. We have another pointer pointing to the end of the merged array which is collecting the number we want to write.
// We compare the elements at pointers P1 and P2, and write the larger one at the positin pointed by col. We then make sure the second array is also completely copied over to the merged array.
//Time Complexity: O(m + n)
//Space Complexity: O(1)

class Solution {
fun merge(nums1: IntArray, m: Int, nums2: IntArray, n: Int): Unit {
var P1 = m - 1
var P2 = n - 1
var col = nums1.size - 1

while (P1 >= 0 && P2 >= 0) {
if(nums1[P1] > nums2[P2]) {
nums1[col] = nums1[P1]
P1--
} else {
nums1[col] = nums2[P2]
P2--
}
col --
}

while(P2 >= 0) {
nums1[col] = nums2[P2]
P2--
col--
}

}
}
24 changes: 24 additions & 0 deletions SearchIn2DMatrix.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
//In this problem, we are starting from the top right corner of the matrix and comparing the current element with the target.
// If the current element is not equal to the target and is greater than the target we move left if its less than the target we move down. We continue this process until we find the target or go out of bounds of the matrix.
//Time Complexity: O(m + n)
//Space Complexity: O(1)

class Solution {
fun searchMatrix(matrix: Array<IntArray>, target: Int): Boolean {
val m = matrix.size
val n = matrix[0].size

var i = 0
var j = n - 1

while(i < m && j >= 0) {
if(matrix[i][j] == target) return true
else if(matrix[i][j] > target) {
j--
}else {
i++
}
}
return false
}
}