Check if Strings Can be Made Equal With Operations I — LeetCode 2839 Python Solution
- Problem
- #2839
- Pattern
- Hash Map
- Reading time
- 2 min
- Source
- leetcode.com
The problem
You are given two strings s1 and s2, both of length 4, consisting of lowercase English letters. You can apply the following operation on any of the two strings any number of times: Choose any two indices i and j such that j - i = 2, then swap the two characters at those indices in the string.
Example
- Input
- s1 = "abcd", s2 = "cdab"
- Output
- true
- Explanation
- We can do the following operations on s1:
Python solution
class Solution:
def canBeEqual(self, s1: str, s2: str) -> bool:
return sorted(s1[::2]) == sorted(s2[::2]) and sorted(s1[1::2]) == sorted(
s2[1::2]
)Complexity
| Measure | Complexity |
|---|---|
| Time | O(n + |\Sigma|) |
| Space | O(|\Sigma|) auxiliary |
Pattern: Hash Map
Trade memory for time: remember what you have seen so the second pass never happens. LeetCode 2839. Check if Strings Can be Made Equal With Operations I is filed here because the reference solution below belongs to the algorithm family this hub collects, even though its LeetCode tags point elsewhere.
The hash map guide has the Python template for the pattern and the 709 LeetCode problems that use it.
Related problems
Frequently asked questions
- How hard is LeetCode 2839. Check if Strings Can be Made Equal With Operations I?
- LeetCode 2839. Check if Strings Can be Made Equal With Operations I is rated Easy on LeetCode.
- What is the time complexity of LeetCode 2839. Check if Strings Can be Made Equal With Operations I?
- The Python solution on this page runs in O(n + |\Sigma|).
- What is the space complexity of LeetCode 2839. Check if Strings Can be Made Equal With Operations I?
- The Python solution on this page uses O(|\Sigma|) auxiliary space.
- What topics does LeetCode 2839. Check if Strings Can be Made Equal With Operations I cover?
- LeetCode 2839. Check if Strings Can be Made Equal With Operations I is tagged String on LeetCode.