CS300 2020 Fall Final Exam 1 PDF
CS300 2020 Fall Final Exam 1 PDF
For this problem, we can sort the array and return the element in the middle,
but it would have O(nlogn) time complexity. Thus we can try following an
approach similar to quicksort. We can choose a random pivot and use the
same partitioning algorithm but we only recur for the side that the median
element is in and stop when we found the median element. This would result
in O(n) average time complexity.
l = 0, r = n - 1
while l <= r
mid = l + (r - 1) / 2
if arr[mid] == searchedNumber
return mid
if arr[mid] < x
l = mid + 1
else r = mid - 1
return -1
Where arr contains the sorted array and searchedNumber is the number we
are searching for. Assuming indexes start from 0.
We could use two while loops where we choose the node in one loop, and
find and remove the nodes that are the same in the other loop, but this would
have O(n^2) time complexity.
This study source was downloaded by 100000770618860 from CourseHero.com on 01-08-2023 14:00:29 GMT -06:00
1
https://www.coursehero.com/file/147828732/CS300-2020-FALL-FINAL-EXAM-1pdf/
CS300 2020 FALL FINAL EXAM
We can also sort the linked list, then go through the nodes and remove a node
if it’s the same as the previous node. This would have O(nlogn) time
complexity.
We can also use a hashset to store the seen nodes. We would iterate through
the nodes and if the current node is in the seen hashset, then we would
remove it. Otherwise, we would add it to the hashset. This would result in O(n)
time complexity but we would be using O(n) additional memory since we are
using a hashset.
The sorting has O(NlogN) time complexity, while the remaining of the
algorithm has O(n) time complexity since we have a for loop that loops N
- 1 times. So the time complexity is O(NlogN + N) but N can be ignored -
> O(NlogN)
This study source was downloaded by 100000770618860 from CourseHero.com on 01-08-2023 14:00:29 GMT -06:00
2
https://www.coursehero.com/file/147828732/CS300-2020-FALL-FINAL-EXAM-1pdf/
Powered by TCPDF (www.tcpdf.org)