Tutorialspoint
Problem
Solution
Submissions

Binary Search Implementation

Certification: Basic Level Accuracy: 0% Submissions: 0 Points: 8

Write a JavaScript program to implement binary search algorithm to find the target value in a sorted array. Return the index of the target if found, otherwise return -1.

Example 1
  • Input: nums = [-1,0,3,5,9,12], target = 9
  • Output: 4
  • Explanation:
    • We search for target 9 in the sorted array.
    • Using binary search, we check the middle element and narrow down the search space.
    • We find that 9 exists at index 4 in the array.
    • Therefore, we return index 4.
Example 2
  • Input: nums = [-1,0,3,5,9,12], target = 2
  • Output: -1
  • Explanation:
    • We search for target 2 in the sorted array.
    • Using binary search, we systematically eliminate half the array in each iteration.
    • After checking all possible positions, 2 is not found in the array.
    • Therefore, we return -1 to indicate the target is not present.
Constraints
  • 1 ≤ nums.length ≤ 10^4
  • -10^4 < nums[i], target < 10^4
  • All integers in nums are unique
  • nums is sorted in ascending order
  • Time Complexity: O(log n)
  • Space Complexity: O(1)
ArraysAlgorithmsHCL TechnologiesSamsung
Editorial

Login to view the detailed solution and explanation for this problem.

My Submissions
All Solutions
Lang Status Date Code
You do not have any submissions for this problem.
User Lang Status Date Code
No submissions found.

Please Login to continue
Solve Problems

 
 
 
Output Window

Don't have an account? Register

Solution Hints

  • Use two pointers: left starting at 0 and right starting at array length - 1
  • Calculate the middle index as (left + right) / 2 in each iteration
  • Compare the middle element with the target value
  • If middle element equals target, return the middle index
  • If middle element is less than target, search in the right half
  • If middle element is greater than target, search in the left half
  • Continue until left pointer exceeds right pointer

Steps to solve by this approach:

 Step 1: Initialize left pointer to 0 and right pointer to array length - 1.

 Step 2: Enter a loop that continues while left is less than or equal to right.
 Step 3: Calculate the middle index using (left + right) / 2.
 Step 4: Compare the element at middle index with the target value.
 Step 5: If they match, return the middle index as the result.
 Step 6: If middle element is smaller than target, update left = mid + 1.
 Step 7: If middle element is larger than target, update right = mid - 1.
 Step 8: If loop ends without finding target, return -1.

Submitted Code :