Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if there are any repeated elements in an array recursively

Tags:

java

c#

recursion

I have to find recursively if there is any repeated element in an integer array v. The method must have the following signature:

boolean hasRepeatedElements(int[] v) 

I can't see any way of doing that recursively without having to define another method or at least another overload to this method (one that takes for example the element to go after or something). At first I thought about checking for the current v if there is some element equal to the first element, then creating a new array with L-1 elements etc. but that seems rather inefficient. Is it the only way?

Am I missing something here?

like image 938
devoured elysium Avatar asked Jan 28 '26 16:01

devoured elysium


2 Answers

I agree that recursion is not terribly necessary here, but it can be used. Do you know quick-sort algorithm? Same divide-and-conquer approach can be taken here.

boolean hasRepeatedElements(list v) 
    if v.length <= 1 return false;
    List less, greater;
    x = v[0];
    for each y in v, except v[0]
        if y == x
            return true;
        else if y < x
            less.add(y);
        else if y > x
            greater.add(y);
    end;
    return hasRepeatedElements(less) || hasRepeatedElements(greater);
end;

You can also add randomization to make algorithm statistically O(n*log(n)).

http://en.wikipedia.org/wiki/Quicksort

like image 97
Nikita Rybak Avatar answered Jan 31 '26 05:01

Nikita Rybak


I'm sure someone out there smarter than me could do this more efficiently, but at least it works.

bool hasRepeatedElements(int[] v)
        {
            if (v.Length > 1)
            {
                int[] subArray = new int[v.Length - 1];
                for (int i = 1; i < v.Length; i++)
                {
                    if (v[0] == v[i])
                        return true;
                    else
                        subArray[i - 1] = v[i];
                }
                return hasRepeatedElements(subArray);
            }

            return false;
        }
like image 29
Laramie Avatar answered Jan 31 '26 05:01

Laramie



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!