Posts

Showing posts from September, 2024

35. Search Insert Position

  Intuition The problem at hand is to find the position where a target value should be inserted in a sorted array. If the target is already present in the array, we return its index. Otherwise, we return the index where it would be inserted to maintain the sorted order. This is a classic problem that can be efficiently solved using binary search due to the sorted nature of the array. Approach Initialization : We start by initializing two pointers,  left  and  right , to the beginning and end of the array, respectively. Binary Search Loop : We enter a loop that continues as long as  left  is less than or equal to  right . Calculate Midpoint : Compute the midpoint  mid  of the current subarray. Comparison : If  nums[mid]  equals the target, we return  mid  because we’ve found the target. If  nums[mid]  is greater than the target, we adjust the  right  pointer to  mid - 1  to search in the left h...

1903. Largest Odd Number in String

  Intuition The goal is to find the largest odd number that can be formed by removing some digits from the right end of the given string num. The key insight is that the largest odd number will be the longest prefix of num that ends with an odd digit. If the last digit is odd, the entire number is the answer. Otherwise, we need to find the rightmost odd digit and return the substring up to that digit. Approach Check the Last Digit: Start by checking if the last digit of num is odd. If it is, return num as it is already the largest odd number. Iterate from the End: If the last digit is even, iterate from the second last digit to the first digit. For each digit, check if it is odd. If an odd digit is found, return the substring of num from the start to this digit (inclusive). Return Empty String: If no odd digit is found in the entire string, return an empty string. Complexity Time complexity:  (O(n)) , where (n) is the length of the string num. This is because we may need to ch...