I have an array of integers, and I need an O(n) algorithm to find if the array contains a number and its square; one pair is sufficient.
I tried to do it myself, but I have only managed to find a solution in O(n2).
I thought about using counting sort, but the memory usage is too big.
Naive Approach: Follow the steps below to solve the problem: Initialize a variable, say, count, to store the required count. Traverse the array and for each and every array element, perform the following operations: Traverse the array and search if the square of the current element is present in the array.
Algorithm is as follows: Divide the number in two parts with one part containing only the number at unit's place say part 'A', and other part say 'B', containing the remaining number. Now square the number at unit's place. The square will be one of these; {0,1,4,9,16,25,36,49,64,81}.
Take input an array of integers in increasing order. An integer function squareAndSort(int *arr, int n) takes input as an array of integers and returns the square of each element of the array in a sorted manner. Initialize two pointers left and right with the left element and rightmost element of the array.
A magic square is an array of numbers having the same number of rows and columns and the sum of numbers in each row, column or diagonal being the same. Fill in the blank cells of the following magic squares: 22. 6. 13.
create a new array twice the length of the input array. O(2N)
copy all of the numbers in O(N)
copy the squares of the numbers in O(N)
radix sort (we can since they are all ints) O(N)
iterate over once to see if there are two numbers the same one after the other O(N)
profit! O(1)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With