Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Algorithm to find a number and its square in an array

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.

like image 283
gillyb Avatar asked Feb 01 '10 20:02

gillyb


People also ask

How do you find a square number in an array?

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.

How do you square a number algorithm?

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}.

How do you square an array in C++?

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.

What is a square array of numbers?

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.


1 Answers

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)

like image 143
Chris H Avatar answered Nov 16 '22 00:11

Chris H