There can be many ways to solve this problem. Else if the square of mid is more than X then search for a smaller value in the first half of the search space, i.e r = mid – 1īelow is the implementation of the above approach:.Check if the square of mid ( mid = (l + r)/2 ) is less than or equal to X, If yes then search for a larger value in the second half of the search space, i.e l = mid + 1, update ans = mid.Run a loop until l Create some variables, for storing the lower bound say l = 0, and for upper bound r = X / 2 (i.e, The floor of the square root of x cannot be more than x/2 when x > 1). Base cases for the given problem are when the given number is 0 or 1, then return X.The values of i * i is monotonically increasing, so the problem can be solved using binary search.īelow is the implementation of the above idea: The idea is to find the largest integer i whose square is less than or equal to the given number. Square root an integer using Binary search: Thanks, Fattepur Mahesh for suggesting this solution. Only one traversal of the solution is needed, so the time complexity is O(√X). Software Engineering Interview Questions.Top 10 System Design Interview Questions and Answers.Top 20 Puzzles Commonly Asked During SDE Interviews.Commonly Asked Data Structure Interview Questions.Top 10 algorithms in Interview Questions.Top 20 Dynamic Programming Interview Questions.Top 20 Hashing Technique based Interview Questions.Top 50 Dynamic Programming (DP) Problems.Top 20 Greedy Algorithms Interview Questions.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |