Bash Script to Find Common Elements in Two Arrays
for i in "${arr1[@]}"; do for j in "${arr2[@]}"; do [[ "$i" == "$j" ]] && echo "$i"; done; done.Examples
How to Think About It
Algorithm
Code
arr1=(1 2 3 4) arr2=(3 4 5 6) for i in "${arr1[@]}"; do for j in "${arr2[@]}"; do if [[ "$i" == "$j" ]]; then echo "$i" fi done done
Dry Run
Let's trace arrays arr1=(1 2 3 4) and arr2=(3 4 5 6) through the code
Start with first element of arr1
i=1; compare with arr2 elements 3,4,5,6; no match
Next element of arr1
i=2; compare with arr2 elements 3,4,5,6; no match
Next element of arr1
i=3; compare with arr2 elements 3,4,5,6; match found at 3; print 3
Next element of arr1
i=4; compare with arr2 elements 3,4,5,6; match found at 4; print 4
| arr1 element | arr2 element | Match? |
|---|---|---|
| 1 | 3 | No |
| 1 | 4 | No |
| 1 | 5 | No |
| 1 | 6 | No |
| 2 | 3 | No |
| 2 | 4 | No |
| 2 | 5 | No |
| 2 | 6 | No |
| 3 | 3 | Yes |
| 3 | 4 | No |
| 3 | 5 | No |
| 3 | 6 | No |
| 4 | 3 | No |
| 4 | 4 | Yes |
| 4 | 5 | No |
| 4 | 6 | No |
Why This Works
Step 1: Nested loops compare elements
The outer loop picks each element from the first array, and the inner loop checks it against every element in the second array.
Step 2: Equality check with <code>==</code>
The script uses [[ "$i" == "$j" ]] to test if elements are the same.
Step 3: Print common elements
When a match is found, the element is printed immediately, showing all common items.
Alternative Approaches
declare -A map arr1=(1 2 3 4) arr2=(3 4 5 6) for i in "${arr1[@]}"; do map["$i"]=1 done for j in "${arr2[@]}"; do if [[ ${map["$j"]} ]]; then echo "$j" fi done
arr1=(apple banana cherry) arr2=(banana grape apple) comm -12 <(printf "%s\n" "${arr1[@]}" | sort) <(printf "%s\n" "${arr2[@]}" | sort)
Complexity: O(n*m) time, O(n) space
Time Complexity
The nested loops cause the script to check each element of the first array against every element of the second, resulting in O(n*m) time.
Space Complexity
The script uses no extra arrays except for input, so space is O(n) for storing the arrays themselves.
Which Approach is Fastest?
Using associative arrays reduces time to O(n+m) by trading space for speed, while nested loops are simpler but slower for large arrays.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Nested loops | O(n*m) | O(n) | Small arrays, simplicity |
| Associative arrays | O(n+m) | O(n) | Large arrays, faster lookup |
| Sorting + comm | O(n log n + m log m) | O(n+m) | When sorting is acceptable and external commands are allowed |