DEV Community

Kushal
Kushal

Posted on • Updated on

[Part - 2: Array] Questions on Array

Questions on Array 📘

Check my part 1 for details on the time complexity in Array Operations

Let's discuss some important questions on array. Common questions to practice. I will be using C# as of now for the questions, but really when it comes to logical questions, language really doesn't holds any importance.

⚠️ I would suggest, you should try along with me. You can use repl.it and select the language of your choice. Just copy paste the functional methods in the class and use it. Also, you can check my git for more such questions. GitHub repository

Will keep on adding questions daily in the same article.

Is array sorted

Checkout if the given array is sorted. The time complexity is Big O(n). You can paste this function in the default c# template in repl. or use this to directly. Gist Link

public static bool IsArraySorted(int[] array)
{
    bool isSorted = false;

    for (int i = 1; i < array.Length; i++)
    {
        if (!(array[i-1] < array[i]))
        {
            isSorted = false;
            break;
        }
        else
        {
            isSorted = true;
        }
    }

    if (array.Length == 0 || array.Length == 1)
        isSorted = true;

    return isSorted;
}
Enter fullscreen mode Exit fullscreen mode

Reverse the array

Reversing an array is like you want first event to be the last element and second element as the last - 1 element. The time complexity of problem is O(n)

        public static int[] ReversedArray(int[] array)
        {
            int j = -1;
            for(int i = array.Length -1; i >= array.Length / 2; i--)
            {
                j++;
                var temp = array[i];
                array[i] = array[j];
                array[j] = temp;
            }
            return array;
        }
Enter fullscreen mode Exit fullscreen mode

Remove duplicates from Array

Removing duplicates from an array comes up with a tricky part. Try it yourself and explore. Time complexity is O(1)

        public static int RemoveDuplicatesFromSortedArray(int[] arr, int arrayLength)
        {
            if (arrayLength == 0 || arrayLength == 1)
                return arrayLength;

            int k = 0;
            for (int i = 0; i < arrayLength - 1; i++)
                if (arr[i] != arr[i + 1])
                    arr[k++] = arr[i];

            arr[k++] = arr[arrayLength - 1];
            return k;
        }
Enter fullscreen mode Exit fullscreen mode

Top comments (0)