710018. Concatenate Equal to Target
Concatenate Equal to Target
Summary
Given an array of strings and a target string, concatenate all strings in the array that are equal to the target string. The output should be a single concatenated string.
The problem involves manipulating arrays of strings and comparing them with a target string, making it a combination of strings and arrays problems.
Detailed Explanation
The approach to solve this problem is to iterate through the input array and concatenate all strings that are equal to the target string. We can use a Map to keep track of the strings we have seen so far and their counts. If the count of a string in the map is equal to 1, it means we have not seen this string before, so we add it to our concatenated result.
Here's a step-by-step breakdown of the solution:
- Initialize an empty string
resultthat will store the concatenated strings. - Iterate through the input array and for each string:
- Check if the string is equal to the target string using a string comparison method (e.g.,
equals()in Java or Python). - If the string is equal to the target, add it to the
resultstring.
- Check if the string is equal to the target string using a string comparison method (e.g.,
- Return the
resultstring.
Here's an ASCII art diagram illustrating the process:
+---------------+
| Input Array |
+---------------+
|
| Iterate through array
v
+---------------+
| Check if each |
| string is equal |
| to the target |
+---------------+
|
| Yes, add to result
v
+---------------+
| Concatenated |
| strings in |
| result |
+---------------+
The time complexity of this solution is O(n), where n is the length of the input array. This is because we are iterating through the array once and performing a constant-time operation for each element.
The space complexity is also O(n) as we are storing the concatenated strings in a single string, which can take up to n characters.
Optimized Solutions
Java
public String concatenateEqual(String[] arr, String target) {
StringBuilder result = new StringBuilder();
Map<String, Integer> map = new HashMap<>();
for (String str : arr) {
if (str.equals(target)) {
result.append(str).append(" ");
map.put(str, map.getOrDefault(str, 0) + 1);
}
}
return result.toString().trim();
}