easyStringsPattern: Basic List Operations
String Character Matcher Solution
Problem Statement
Given two strings, determine the common characters between them and return them in a list, maintaining the original order from the first string.
Examples
Example 1:
Input:{"str1":"abcde","str2":"ace"}
Output:["a","c","e"]
Explanation: The characters 'a', 'c', and 'e' are common to both strings and appear in that order in the first string.
Example 2:
Input:{"str1":"hello","str2":"world"}
Output:["l","o"]
Explanation: The characters 'l' and 'o' are the common characters between 'hello' and 'world', in the order they appear in 'hello'.
Constraints
- The length of each input string is less than or equal to 100.
- Input strings only contain lowercase English letters.
- Each character in the output list must be unique.
Time: O(n) Space: O(n)
An optimized approach involves creating a set from the second string for O(1) lookup times, then iterating through the first string to find common characters, resulting in a time complexity of O(n).
Run, Test & Submit Code
Ready to practice this challenge? Launch our interactive compilation environment with compiler validation.
Solve on Interactive WorkspaceTested Solutions
No solution code is currently loaded.
Complete this code in the workspace editor.
