Created
April 24, 2021 23:21
-
-
Save charleslukes/c7b7d59daab3c718b0b6223588310c89 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
let num = [0,8,-2,5,0]; | |
let val = 0; | |
const startAndEndOfVal = (numArr: Array<number>, val: number) => { | |
let indexes = numArr.sort().reduce((acc: Array<number>, cur: number, index: number) => { | |
if(cur === val){ | |
acc.push(index) | |
} | |
return acc | |
}, []); | |
if(indexes.length === 0) { | |
return [-1, -1]; | |
} | |
return [indexes[0], indexes[indexes.length - 1]]; | |
} | |
console.log(startAndEndOfVal(num, val)); |
Hello @charleslukes, this is a really interesting solution. You were able to implement the merge-sort, that is amazing!
That said, do you think there's a way we could have solved this problem without having to sort the array?
I have written a blog post here sharing my solution to this problem - a solution that avoids sorting the array. Please read through and let me know what you think.
I hope this was a good learning experience for you. Thank you once again for participating once again and see you on Friday for Week 4 of #AlgorithmFridays.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Yes @meekg33k I agree with your concern, sort function is not the most efficient.
And according to MDN
The time and space complexity of the sort cannot be guaranteed as it depends on the implementation.
.Also looking at my algo again there is a subtle error, I forgot to add the comparator for the sort function, this will only be noticeable for some kind of numbers eg
[40, 100, 10, 200]
which will be[ 10, 100, 200, 40 ]
when sorted.I did some research and found bubble sort, it looks fast but worst case senerio for bubble sort is n2 which is not as efficient as sort function see comparison table https://en.wikipedia.org/wiki/Sorting_algorithm.
To get an efficient algorithm (in my view) for this merge sort seems like the way to go.
Here is my update: