DEV Community

codingpineapple
codingpineapple

Posted on

1 1

34. Find First and Last Position of Element in Sorted Array (javascript solution)

Description:

You are given a string s and an integer k. You can Given an array of integers nums sorted in ascending order, find the starting and ending position of a given target value.

If target is not found in the array, return [-1, -1].

You must write an algorithm with O(log n) runtime complexity.

Solution:

Time Complexity : O(nlog(n))
Space Complexity: O(1)

var searchRange = function(nums, target) {
    const output = []

    // find lower bounds
     let l1 = 0, r1 = nums.length;
    while(l1 < r1) {
        const mid = l1 + Math.floor((r1-l1)/2)
        if(nums[mid] >= target) r1 = mid
        else l1 = mid+1
    }
    // if we can't find target in the array then return [-1,-1]
    if(nums[l1]!==target) return [-1,-1]

    // if we did find target, push the lower bound into the output array and search for the upper bound index
    output.push(l1)

    // find upper bounds
    let l2 = l1, r2 = nums.length;
    while(l2 < r2) {
        const mid = l2 + Math.floor((r2-l2)/2)
        if(nums[mid] <= target) l2 = mid+1
        else r2 = mid
    }
    // pointers will meet at the index above the upper bound index, push in the index 1 less than where they meet
    output.push(l2-1)

    return output
};
Enter fullscreen mode Exit fullscreen mode

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay