Skip to content

Commit

Permalink
Solve smallest letter greater than target
Browse files Browse the repository at this point in the history
  • Loading branch information
sangaryousmane committed Jun 5, 2023
1 parent 6167578 commit 03c2952
Show file tree
Hide file tree
Showing 3 changed files with 24 additions and 21 deletions.
Binary file modified out/production/java-interview-questions/Main.class
Binary file not shown.
6 changes: 3 additions & 3 deletions src/Main.java
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,9 @@ public class Main {

public static void main(String[] args) {

int[] arr = {1,2,4,5};
int target = 3;
int result = Searching.searchInsertPosition(arr, target);
char[] arr = {'x','x','y', 'y'};
char target = 'x';
char result = Searching.nextGreatestLetter(arr, target);
System.out.println(result);
}

Expand Down
39 changes: 21 additions & 18 deletions src/intermediate/Searching.java
Original file line number Diff line number Diff line change
Expand Up @@ -85,24 +85,6 @@ else if (n < current) {
return (int) end;
}

// https://leetcode.com/problems/find-smallest-letter-greater-than-target
public char nextGreatestLetter(char[] letters, char target) {
int start = 0;
int end = letters.length - 1;
char ans = letters[0];

while (start <= end) {
int middle = start + (end - start) / 2;

if ((letters[middle] == target) || (target > letters[middle])) {
start = middle + 1;
} else if (letters[middle] > target) {
ans = letters[middle];
end = middle - 1;
}
}
return ans;
}

// https://leetcode.com/problems/binary-search/
public static int binarySearch(int[] nums, int target) {
Expand Down Expand Up @@ -347,6 +329,9 @@ public static int kthMissingPositiveNumber(int arr[], int k) {
public static int searchInsertPosition(int [] arr, int target){
int start = 0, end = arr.length - 1;

if (target > arr[end]){
return -1;
}
while (start <= end){
int middle = start + (end - start) / 2;

Expand Down Expand Up @@ -386,4 +371,22 @@ else if (nums[middle] < target){
}
return end;
}
// https://leetcode.com/problems/find-smallest-letter-greater-than-target/description/
public static char nextGreatestLetter(char[] letters, char target){
int n = letters.length; // Length of the character array
int start = 0, end = n - 1;

while (start <= end){
int middle = start + (end - start) / 2;

if (letters[middle] > target){
end = middle - 1;
}
else{
start = middle + 1;
}
}
return letters[start % n];
}

}

0 comments on commit 03c2952

Please sign in to comment.