0

I have an array as: ["Front", "Front", "Back", "Back", "Side", Side]

What I need to do is return the indices for all matching occurrences of a particular string. For example, if inputting: "Front" it should return [0,1], input "Side", should return [4,5] and "Back" would return [2,3]

How can this be accomplished in Java efficiently?

Sauron
  • 6,399
  • 14
  • 71
  • 136
  • 2
    There is not other way more efficient than looping it once and getting its indexes when it found using `equals()` which is O(n). – Rod_Algonquin Mar 31 '15 at 03:33
  • 1
    Note that it also depends on the characteristics of the input array itself. For example, if all the equal words are contiguous, or better yet, sorted, there would be ways to optimize. If it's random, then O(n) is your only choice. – mprivat Apr 07 '15 at 07:01

1 Answers1

1

Try this

    String inPut="Side";

    String data [] = {"Front", "Front", "Back", "Back", "Side", "Side"};

    ArrayList positions=new ArrayList();

    for(int i=0;i<data.length;i++)
    {
        if(inPut.equals(data[i]))
        {
            positions.add(i);
        }
    }

    System.out.println(positions);
} 

output

[4, 5]

Try with changed inputs

Anptk
  • 1,125
  • 2
  • 17
  • 28