Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
const startAndStopPosition = (nums, val) => {
if(!Array.isArray(nums) || nums.length === 0) return [-1, -1];
// Initialization of Variables
let initialIndex = 0;
let count = 0;
let startAndStop = [];
// Looping through the array;
for(let i = 0; i < nums.length; i++) {
if(nums[i] < val) {
initialIndex += 1;
}
if(nums[i] === val) {
count += 1;
}
}
if(count === 0) {
startAndStop.push(-1, -1);
}else {
startAndStop.push(initialIndex, (count - 1) + initialIndex);
}
return startAndStop;
}
@meekg33k

This comment has been minimized.

Copy link

@meekg33k meekg33k commented Apr 25, 2021

Hi @tobi-bams, thank you for participating in Week 3 of #AlgorithmFridays.

Your solution looks really neat in terms of correctness and robustness especially because you handled the edge cases really well. However, what do you think is the time complexity for solution? Is it possible to come up with a solution that doesn't require sorting the array?

@tobi-bams

This comment has been minimized.

Copy link
Owner Author

@tobi-bams tobi-bams commented Apr 25, 2021

Thank you so much @meekg33k.

My previous solution will definitely take more time, all thanks to you i was able to think then i came up with a solution that does not require sorting the array.

I just updated my solution.

Thanks a lot i really appreciate!!

@meekg33k

This comment has been minimized.

Copy link

@meekg33k meekg33k commented Apr 27, 2021

Awesome! This is a more optimal solution and yes, you really don't have to sort the array for this problem; I'm glad you were able to see that.

Because you were able to come up with this solution, you have been selected as one of the winners of the $20 award for Week 3 of #AlgorithmFridays. 🎉🎉

I have written an in-depth blog post here about this solution; the post also announces you as one of the winners. Please read through and let me know what you think.

Thank you for participating once again and see you on Friday for Week 4 of #AlgorithmFridays.

@tobi-bams

This comment has been minimized.

Copy link
Owner Author

@tobi-bams tobi-bams commented Apr 29, 2021

Thank you so much @meekg33k this really helped open my mind.......

Looking forward to the next challenge

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment