Skip to content

Instantly share code, notes, and snippets.

@virengujariya
Last active July 9, 2018 17:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save virengujariya/565de826ce04438bf32a24cf36f9f317 to your computer and use it in GitHub Desktop.
Save virengujariya/565de826ce04438bf32a24cf36f9f317 to your computer and use it in GitHub Desktop.
Data structure and algorithms

Given array of positive items = {1, 2, 3, 4, 4} the simplest brute force solution could be as per below. However, this solution has Time complexity O(n^2)

Do you think there is better solution? Let's find out.

public class Test {
    public static int find(int[] items) {
        int length = items.length;
        for (int i = 0; i < length; i++) {
            for (int j = 0; j < length; j++) {
                if (items[i] == items[j] && i != j) {
                    return items[i];
                }
            }
        }
        return -1;
    }
}

Couple of things to discuss:

  1. Time Complexity https://www.studytonight.com/data-structures/time-complexity-of-algorithms
  2. Data structure and algorithms
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment