Problem Description: Spin-off of this kata, here you will have to figure out an efficient strategy to solve the problem of finding the sole duplicate number among an unsorted array/list of numbers starting from 1 up to n.
Hints: a solution in linear time can be found; using the most intuitive ones to search for duplicates that can run
in O(n²) time won't work.
Level:6kyu
Link To Kata: Finding duplicate in an unsorted list in O(n) time
This kata demands complexity less than O(n²). So we cannot sort this function using Javascript prototype also we cannot use 2 for loops to check for a duplicate value.
We start solving this kata by finding the maximum value in the given array. Then we define an array of length of maximum value in which every element is initialized to zero.
We loop through the initial array and for every value in the array we map its value in our initialized array. If it is zero then we make it 1. But if its already 1 then we return the value at index of the input array as the duplicate value.
Please go through the code for a better understanding.
Here is the link to code: Kata Day 49
Please mention your suggestions or your doubts in the comment below.
Happy coding. :)
No comments:
Post a Comment