0% found this document useful (0 votes)
12 views10 pages

Dec 19,2024 (LBQ-Search Insert Position, Missing Numbers)

Excellent
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views10 pages

Dec 19,2024 (LBQ-Search Insert Position, Missing Numbers)

Excellent
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 10

Galgotias College of Engineering & Technology, Greater Noida

CSE-Training & Development Center

Logic Building Questions


Search Insert Position
Given a sorted array of distinct integers and a target value, return the index
if the target is found. If not, return the index where it would be if it were
inserted in order. You must write an algorithm with O(log n) runtime
1 L
complexity.
1
Example 1:
Input: nums = [1,3,5,6], target = 5
Output: 2

Example 2:
Input: nums = [1,3,5,6], target = 2
Output: 1

Example 3:
Input: nums = [1,3,5,6], target = 7
Output: 4

Constraints:
1 <= nums.length <= 10^4
-10^4 <= nums[i] <= 10^4
nums contains distinct values sorted in ascending order.
-10^4 <= target <= 10^4
Solution The problem can be solved using a Binary Search Algorithm to achieve
(Example 1) the required O (log n) time complexity. Here's how the algorithm works:

1. Use two pointers, left and right, to represent the range of indices in
the array to search.
2. Calculate the middle index mid of the current range.
3. Compare nums[mid] with the target:
o If nums[mid] equals the target, return mid.
o If nums[mid] is less than the target, move the left pointer to
mid + 1.
o If nums[mid] is greater than the target, move the right
pointer to mid - 1.
4. Repeat steps 2–3 until left exceeds right.
5. If the loop ends without finding the target, left will indicate the
index where the target should be inserted.

Code class Solution {


Implementatio public int searchInsert (int[] nums, int target) {
n (Example 1) int left = 0, right = nums.length - 1;
Galgotias College of Engineering & Technology, Greater Noida

CSE-Training & Development Center

while (left <= right) {


int mid = left + (right - left) / 2; // Avoid potential overflow
if (nums[mid] == target) {
return mid;
} else if (nums[mid] < target) {
left = mid + 1;
} else {
right = mid - 1;
}
}

// If not found, left points to the insertion index


return left;
}
}
Solution Approach:
(Example 2)
1. Use binary search to locate the target in the sorted array nums.
2. If the target is found, return its index.
3. If the target is not found, return the index where it would be
inserted to maintain the order.

Java Code class Solution {


public int searchInsert(int[] nums, int target) {
Implementatio
int left = 0, right = nums.length - 1;
n
while (left <= right) {
(Example 2) int mid = left + (right - left) / 2; //
Calculate mid, avoid overflow
if (nums[mid] == target) {
return mid; // Target found
} else if (nums[mid] < target) {
left = mid + 1; // Target is in the right
half
} else {
right = mid - 1; // Target is in the left
half
}
}

// If not found, 'left' will be the insertion point


return left;
}
}
Usage public class Main {
public static void main(String[] args) {
Solution solution = new Solution();
Galgotias College of Engineering & Technology, Greater Noida

CSE-Training & Development Center

// Example 1
(Example 2) int[] nums1 = {1, 3, 5, 6};
int target1 = 2;
System.out.println(solution.searchInsert(nums1,
target1)); // Output: 1

// Example 2
int[] nums2 = {1, 3, 5, 6};
int target2 = 7;
System.out.println(solution.searchInsert(nums2,
target2)); // Output: 4

// Example 3
int[] nums3 = {1, 3, 5, 6};
int target3 = 0;
System.out.println(solution.searchInsert(nums3,
target3)); // Output: 0

// Example 4
int[] nums4 = {1, 3, 5, 6};
int target4 = 5;
System.out.println(solution.searchInsert(nums4,
target4)); // Output: 2
}
}

Explanation of Example 2:

Input: nums = [1,3,5,6], target = 2

1. Start with left = 0, right = 3.


2. Compute mid = (0 + 3) / 2 = 1. nums[mid] = 3.
o Since nums[mid] > target, move right to mid - 1 = 0.
3. Compute mid = (0 + 0) / 2 = 0. nums[mid] = 1.
o Since nums[mid] < target, move left to mid + 1 = 1.
4. The loop ends as left > right, and left = 1 is the insertion
point.

Output: 1.

Complexity:

 Time Complexity: O(log n) , as the binary search divides the range


in half each iteration.
 Space Complexity: O(1), as no extra space is used.
Galgotias College of Engineering & Technology, Greater Noida

CSE-Training & Development Center

(Example 3) Input:
nums = [1, 3, 5, 6]
target = 7

Steps:

1. The target 7 is not in the array, so we need to determine its correct


insertion index.
2. The target 7 is greater than all elements in the array. Therefore, its
insertion index will be at the end of the array, which is 4.

Java Code class Solution {


Implementatio public int searchInsert(int[] nums, int target) {
n int left = 0, right = nums.length - 1;

(Example 3) while (left <= right) {


int mid = left + (right - left) / 2; // Calculate mid to prevent overflow
if (nums[mid] == target) {
return mid; // Target found
} else if (nums[mid] < target) {
left = mid + 1; // Target is in the right half
} else {
right = mid - 1; // Target is in the left half
}
}

// If target is not found, 'left' will be the correct insertion index


return left;
}
}
Usage public class Main {
public static void main(String[] args) {
(Example 3) Solution solution = new Solution();

// Example 3
int[] nums = {1, 3, 5, 6};
int target = 7;
System.out.println(solution.searchInsert(nums, target)); // Output: 4
}
}
1. Initial pointers: left = 0, right = 3.
2. Compute mid = (0 + 3) / 2 = 1. nums[mid] = 3.
o Since nums[mid] < target, move left = mid + 1 = 2.
3. Compute mid = (2 + 3) / 2 = 2. nums[mid] = 5.
Galgotias College of Engineering & Technology, Greater Noida

CSE-Training & Development Center

Since nums[mid] < target, move left = mid + 1 = 3.


o
4. Compute mid = (3 + 3) / 2 = 3. nums[mid] = 6.
o Since nums[mid] < target, move left = mid + 1 = 4.
5. Now left > right, so the loop ends. The insertion index is left = 4.

Output: 4.
2 Missing Number

Given an array nums containing n distinct numbers in the range [0, n],
return the only number in the range that is missing from the array.

Example 1:
Input: nums = [3,0,1] L
Output: 2 2
Explanation: n = 3 since there are 3 numbers, so all numbers are in the
range [0,3]. 2 is the missing number in the range since it does not appear in
nums.
Example 2:
Input: nums = [0,1]
Output: 2
Explanation: n = 2 since there are 2 numbers, so all numbers are in the
range [0,2]. 2 is the missing number in the range since it does not appear in
nums.
Example 3:
Input: nums = [9,6,4,2,3,5,7,0,1]
Output: 8
Explanation: n = 9 since there are 9 numbers, so all numbers are in the
range [0,9]. 8 is the missing number in the range since it does not appear in
nums.
Constraints:

n == nums.length
1 <= n <= 104
0 <= nums[i] <= n
All the numbers of nums are unique.
Solution Approach
(Example 1)
We can solve this problem using the Sum Formula for the first nnn natural
numbers:
Galgotias College of Engineering & Technology, Greater Noida

CSE-Training & Development Center

 Calculate the actual sum of the array elements.


 The difference between the expected sum and the actual sum gives the
missing number.

Complexity

 Time Complexity: O(n), as we iterate through the array once.


 Space Complexity: O(1), no additional data structures are used.

Code class Solution {


Implementatio public int missingNumber(int[] nums) {
int n = nums.length;
n (Example 1)
// Calculate the expected sum of the first n natural
numbers
int expectedSum = n * (n + 1) / 2;

// Calculate the actual sum of the array elements


int actualSum = 0;
for (int num : nums) {
actualSum += num;
}

// The missing number is the difference


return expectedSum - actualSum;
}
}

Example Usage
public class Main {
public static void main(String[] args) {
Solution solution = new Solution();

int[] nums1 = {3, 0, 1};

System.out.println(solution.missingNumber(nums1)); //
Output: 2

int[] nums2 = {0, 1};

System.out.println(solution.missingNumber(nums2)); //
Galgotias College of Engineering & Technology, Greater Noida

CSE-Training & Development Center

Output: 2

int[] nums3 = {9,6,4,2,3,5,7,0,1};

System.out.println(solution.missingNumber(nums3)); //
Output: 8

int[] nums4 = {0};

System.out.println(solution.missingNumber(nums4)); //
Output: 1
}
}

1. Expected Sum:
o Compute the sum of numbers from 000 to nnn using the
formula n×(n+1)/2
2. Actual Sum:
o Traverse the array and compute the sum of its elements.
3. Missing Number:
o The missing number is simply expectedSum − actualSum

Solution 1. Sum Formula Approach


(Example 2)
The sum of the first nnn natural numbers is given by: sum=n×(n+1)2\
text{sum} = \frac{n \times (n + 1)}{2}sum=2n×(n+1)

 Calculate the sum of numbers in the range [0,n][0, n][0,n] using the
formula.
 Calculate the actual sum of the array elements.
 The difference between the two sums gives the missing number.

Java Code (Sum class Solution {


Formula) public int missingNumber(int[] nums) {
int n = nums.length;
// Calculate the expected sum of numbers from 0 to n
int expectedSum = n * (n + 1) / 2;

// Calculate the actual sum of array elements


int actualSum = 0;
for (int num : nums) {
actualSum += num;
}
Galgotias College of Engineering & Technology, Greater Noida

CSE-Training & Development Center

// The missing number is the difference


return expectedSum - actualSum;
}
}
Another 2. XOR Approach
Approach
(Example 2) Another efficient way to solve this is using the XOR operation:

 XOR all the numbers from 000 to nnn.


 XOR the result with all the numbers in the array.
 The result will be the missing number, as duplicate XOR cancels out
numbers.

Usage class Solution {


(Example 2) public int missingNumber(int[] nums) {
int n = nums.length;
int xor = 0;

// XOR all numbers from 0 to n


for (int i = 0; i <= n; i++) {
xor ^= i;
}

// XOR with all elements in the array


for (int num : nums) {
xor ^= num;
}

// The result is the missing number


return xor;
}

}
public class Main {

public static void main(String[] args) {

Solution solution = new Solution();


Galgotias College of Engineering & Technology, Greater Noida

CSE-Training & Development Center

int[] nums1 = {0, 1};

System.out.println(solution.missingNumber(nums1)); //
Output: 2

int[] nums2 = {3, 0, 1};

System.out.println(solution.missingNumber(nums2)); //
Output: 2

int[] nums3 = {9, 6, 4, 2, 3, 5, 7, 0, 1};

System.out.println(solution.missingNumber(nums3)); //
Output: 8

}
}
Input: nums = [0, 1], n=2

1. Sum Formula:
o Expected sum: (2x(2+1))/2 = 3
o Actual sum: 0+1=1
o Missing number: 3−1=2

2. XOR Method:
o XOR from 0 to 2: 0⊕1⊕2=3
o XOR with array elements: 3⊕0⊕1=2
o Missing number: 2.

Complexity:

 Time Complexity: O(n) for both approaches, as we iterate through the


array once.
Galgotias College of Engineering & Technology, Greater Noida

CSE-Training & Development Center

 Space Complexity: O(1), no extra space is used.

You might also like