troubleshooting Question

C# solution with O(n) time complexity and O(1) additional space complexity

Avatar of CipherIS
CipherISFlag for United States of America asked on
.NET ProgrammingC#
4 Comments1 Solution145 ViewsLast Modified:
Working on a puzzle.

Given an array a that contains only numbers in the range from 1 to a.length, find the first duplicate number for which the second occurrence has the minimal index. In other words, if there are more than 1 duplicated numbers, return the number for which the second occurrence has a smaller index than the second occurrence of the other number does. If there are no such elements, return -1.

Below are some sample array's which are being tested.  So, in the code I have when this array  { 2, 4, 3, 5, 1 } reaches 5 I get an out of bound error which makes sense.  Any idea how to solve?
        private void Form1_Load(object sender, EventArgs e)
        {
            int[] a = new int[]{2, 3, 3, 1, 5, 2};
            a = new int[] { 2, 4, 3, 5, 1 };
            a = new int[] {1};

            //Console.Write("The first repeating elements is: ");

            Console.Write("Repeated Elements are :");
            //for (int i = 0; i < a.Length; i++)
            //{
            //    for (int j = i + 1; j < a.Length; j++)
            //    {
            //        if (a[i] == a[j])
            //            Console.Write(a[i] + " ");
            //    }
            //}

            for (int i = 0; i < a.Length; i++)
            {
                if (a[Math.Abs(a[i])] >= 0)
                {
                    a[Math.Abs(a[i])] = -a[Math.Abs(a[i])];
                    //Console.WriteLine("IF: " + a[Math.Abs(a[i])]);
                }
                else
                {
                    Console.Write(Math.Abs(a[i]) + " ");
                    break;
                }
            }         
        }
ASKER CERTIFIED SOLUTION
Misha
Programmer

Our community of experts have been thoroughly vetted for their expertise and industry experience.

Join our community to see this answer!
Unlock 1 Answer and 4 Comments.
Start Free Trial
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 4 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros