File tree Expand file tree Collapse file tree
Expand file tree Collapse file tree Original file line number Diff line number Diff line change 1+ """
2+ Problem: Close Strings
3+
4+ Two strings are considered "close" if:
5+ 1. They have the same set of characters
6+ 2. Their character frequencies can be rearranged to match
7+
8+ This implementation uses dictionaries (no Counter).
9+ """
10+
11+
12+ class Solution :
13+ def closeStrings (self , word1 : str , word2 : str ) -> bool :
14+ # Step 1: If lengths are different → cannot be close
15+ if len (word1 ) != len (word2 ):
16+ return False
17+
18+ # Step 2: Create frequency dictionaries
19+ dici1 = {}
20+ dici2 = {}
21+
22+ # Count frequency of characters in word1
23+ for i in word1 :
24+ if i in dici1 :
25+ dici1 [i ] += 1
26+ else :
27+ dici1 [i ] = 1
28+
29+ # Count frequency of characters in word2
30+ for i in word2 :
31+ if i in dici2 :
32+ dici2 [i ] += 1
33+ else :
34+ dici2 [i ] = 1
35+
36+ # Step 3: Check if both words have same unique characters
37+ # If not → cannot transform one into another
38+ if set (dici1 .keys ()) != set (dici2 .keys ()):
39+ return False
40+
41+ # Step 4: Compare sorted frequency values
42+ # Order doesn't matter, only distribution matters
43+ return sorted (dici1 .values ()) == sorted (dici2 .values ())
44+
45+
46+ # -----------------------------------
47+ # Example Test Cases
48+ # -----------------------------------
49+ if __name__ == "__main__" :
50+ sol = Solution ()
51+
52+ print (sol .closeStrings ("abc" , "bca" )) # True
53+ print (sol .closeStrings ("aabb" , "bbcc" )) # False
54+ print (sol .closeStrings ("cabbba" , "abbccc" )) # True
Original file line number Diff line number Diff line change 1313for i in range (n - 1 ,- 1 ,- 1 ):
1414 post [i ]*= postfix
1515 postfix *= nums [i ]
16- print (post )
16+ print (post )
17+
You can’t perform that action at this time.
0 commit comments