Contents

Similarity of arrays (with.Java)

   Mar 2, 2024     2 min read

This article examines the “Similarity of Arrays” problem.

As I solve coding test problems, I look back on the problems I solved and look into different solution methods to learn more.

Let’s look at the problem first.

problem

I’m trying to see how similar the two arrays are.

Given string arrays s1 and s2, complete the solution function to return the same number of elements.

Restrictions

  • 1 ≤ s1, length of s2 ≤ 100
  • Length of elements of 1 ≤ s1, s2 ≤ 10
  • The elements of s1 and s2 consist of only lowercase alphabet letters.
  • s1 and s2 each have no duplicate elements.

Input/Output Example

s1s2result
[“a”, “b”, “c”][“com”, “b”, “d”, “p”, “c”]2
[“n”, “omg”][“m”, “dot”]0

My solution to the problem

class Solution {
     public int solution(String[] s1, String[] s2) {
         int answer = 0;
         for(int i = 0; i < s1.length; i++){
             for(int j = 0; j < s2.length; j++){
                 answer += s1[i].equals(s2[j]) ? 1:0;
             }
         }
         return answer;
     }
}

Solution explanation

  • This method is executed by receiving two string arrays s1 and s2 as arguments.
  • Inside the method, a variable called answer is initialized to 0, and a double loop is used to compare each element of the s1 array with each element of the s2 array.
  • If the two strings are the same, add 1 to the answer, and if they are different, add 0.
  • Finally, the value of the answer variable is returned.
  • This value indicates how many values are the same in the s1 array and s2 array.
  • For example, if the s1 array is [“apple”, “banana”, “orange”] and the s2 array is [“banana”, “orange”, “grape”], then the same values in the s1 and s2 arrays are “ There are two in total: “banana” and “orange.”
  • The solution method will return 2.