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
33 changes: 33 additions & 0 deletions RotatedSearchArray.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
//Time complexity: O(log n) where n is the number of elements in the array
//Space complexity: O(1) as we are using constant space to store the indices
class RotatedSearchArray {
fun search(nums: IntArray, target: Int): Int {
var left = 0
var right = nums.size - 1

while (left <= right) {
val mid = left + (right - left) / 2

if (nums[mid] == target) {
return mid
}

// Check if the left half is sorted
if (nums[left] <= nums[mid]) {
if (target >= nums[left] && target < nums[mid]) {
right = mid - 1
} else {
left = mid + 1
}
} else { // Right half is sorted
if (target > nums[mid] && target <= nums[right]) {
left = mid + 1
} else {
right = mid - 1
}
}
}

return -1
}
}
29 changes: 29 additions & 0 deletions Search2DMatrix.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
//Time complexity: O(m+n) where m is the number of rows and n is the number of columns in the matrix
//Space complexity: O(1) as we are using constant space to store the indices
class Search2DMatrix {
fun searchMatrix(matrix: Array<IntArray>, target: Int): Boolean {

if(matrix.isEmpty() || matrix[0].isEmpty()) return false

var i = 0
var j = matrix[0].size-1

while(i < matrix.size && j >= 0){

if(matrix[i][j] == target){
return true
}
else{
if(target < matrix[i][j]){
j-=1
}else{
i+=1
}
}

}


return false
}
}
27 changes: 27 additions & 0 deletions SearchArrayUnknownSize.kt
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@

class SearchArrayUnknownSize {
fun search(reader: ArrayReader, target: Int): Int {
var low = 0
var high = 1

while (reader.get(high) < target) {
low = high
high *= 2
}

while (low <= high) {
val mid = low + (high - low) / 2
val value = reader.get(mid)

if (value == target) {
return mid
} else if (value < target) {
low = mid + 1
} else {
high = mid - 1
}
}

return -1
}
}