question_slug
stringlengths
3
77
title
stringlengths
1
183
slug
stringlengths
12
45
summary
stringlengths
1
160
author
stringlengths
2
30
certification
stringclasses
2 values
created_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
updated_at
stringdate
2013-10-25 17:32:12
2025-04-12 09:38:24
hit_count
int64
0
10.6M
has_video
bool
2 classes
content
stringlengths
4
576k
upvotes
int64
0
11.5k
downvotes
int64
0
358
tags
stringlengths
2
193
comments
int64
0
2.56k
isomorphic-strings
Java solution with 1 line core code
java-solution-with-1-line-core-code-by-y-u4t3
public boolean isIsomorphic(String s1, String s2) {\n Map<Character, Integer> m1 = new HashMap<>();\n Map<Character, Integer> m2 = new Has
yfcheng
NORMAL
2015-12-25T22:40:41+00:00
2015-12-25T22:40:41+00:00
16,905
false
public boolean isIsomorphic(String s1, String s2) {\n Map<Character, Integer> m1 = new HashMap<>();\n Map<Character, Integer> m2 = new HashMap<>();\n \n for(Integer i = 0; i < s1.length(); i++) {\n \n if(m1.put(s1.charAt(i), i) != m2.put(s2.charAt(i), i)) {\n return false;\n }\n }\n return true;\n }
96
2
[]
12
isomorphic-strings
Simple solution using one Hashmap.
simple-solution-using-one-hashmap-by-sat-bsvn
ALGORITHM\n1. Insert chars of string s as key, and chars of t as value , into a map. For ex. if s = foo and t = baa contents of map should be\'f\'-\'b\' , \'
satyyaa98
NORMAL
2021-04-19T10:18:04.371408+00:00
2021-04-19T10:18:04.371454+00:00
9,108
false
**ALGORITHM**\n1. Insert chars of string ```s``` as key, and chars of ```t``` as value , into a map. For ex. if ```s = foo and t = baa``` contents of map should be``` \'f\'-\'b\' , \'o\'-\'a\' ```.\n2. Before inserting, check for the presence of the key:\n\tif present check for the values of the corresponding chars in ```t``` and map\'s value, i.e ```map[s[i]] != t[i]``` return false else continue to next index.\n\t\n\tThe above steps work for the given eg. test cases, but for ```s= badc and t = baba``` the map results in the following content:``` \'b\'-\'b\' , \'a\'-\'a\' , \'d\'-\'a\', \'c\'-\'a\' ``` and return true as answer. \n\tSo to avoid test cases having "many to one" key value pair, the function is called by interchanging ```s and t``` , for the above case now ``` s= baba and t= badc```when character``` b ``` of string ```s``` is processed for the second time ```map[s[i]] = b``` but ```t[i]= d``` which are not same, hence returns false.\n\t\n\t```\n\tbool helper(string s,string t){\n map<char,char>mp;\n for(int i=0;i<s.size();i++){\n if(mp.find(s[i])!=mp.end()){\n if(mp[s[i]]!=t[i]) return false;\n }\n else mp[s[i]]=t[i];\n }\n return true;\n }\n\t\n bool isIsomorphic(string s, string t) {\n return helper(s,t) && helper(t,s);\n }\n\t```
92
1
['C']
12
isomorphic-strings
Easy JS Sol. || 99.14% acceptable || Understandable Approach 💯🧑‍💻
easy-js-sol-9914-acceptable-understandab-6s3q
Intuition\n Describe your first thoughts on how to solve this problem. \n\n- Loop through the input strings and apply the conditions.\n\n# Approach\n Descri
Rajat310
NORMAL
2023-01-31T05:01:44.010371+00:00
2023-09-26T19:11:58.090611+00:00
4,966
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n- Loop through the input strings and apply the conditions.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n1. The **approach** of the function is to compare the positions of characters in the two input strings, `s` and `t`, and `check if they are the same`. \n2. The function loops through each character in `s` and uses the **indexOf** method to find the next occurrence of the current character in both `s` and `t`. \n3. If the positions of the next occurrences of the current character in both strings are **not the same**, the function **returns** **false**, indicating that the strings are `not isomorphic`. \n4. If the loop completes without returning false, the function **returns true**, indicating that the strings are `isomorphic`.\n\n# Complexity\n- Time complexity: $$O(N^2)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n1. Here N is the length of the input strings. \n2. This is because the code uses the indexOf method, which has a time complexity of O(N) in the worst case.\n3. Since this method is used twice in the code (once for s and once for t), the total time complexity is $$O(N^2)$$.\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n1. Because it does not use any data structures with a size proportional to the input size.\n2. It only uses variables for loop indices, which have a constant size.\n\n\n\n\n# Code\n```\n/**\n * @param {string} s\n * @param {string} t\n * @return {boolean}\n */\nvar isIsomorphic = function(s, t) {\n\n for (let i=0; i<s.length; i++) {\n\n if (s.indexOf(s[i], i + 1) !== t.indexOf(t[i], i + 1)) {\n \n return false;\n }\n }\n return true;\n};\n\n// For enquiry about what is indexOf method, go to MDN.\n\n// (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)\n\n```\n\n![cat img for upvote on LC.jpeg](https://assets.leetcode.com/users/images/f89e01b8-99b2-473c-9acb-3e9a1b3d94cd_1678518883.4912484.jpeg)\n
78
0
['Hash Table', 'String', 'JavaScript']
7
isomorphic-strings
My C 0ms solution
my-c-0ms-solution-by-rxm24217-bqgx
bool isIsomorphic(char* s, char* t) {\n \tchar charArrS[256] = { 0 };\n \tchar charArrT[256] = { 0 };\n \tint i = 0;\n \twhile (s[i] !=0)\n \t{\n
rxm24217
NORMAL
2015-05-26T14:28:04+00:00
2018-09-11T22:10:45.887993+00:00
15,073
false
bool isIsomorphic(char* s, char* t) {\n \tchar charArrS[256] = { 0 };\n \tchar charArrT[256] = { 0 };\n \tint i = 0;\n \twhile (s[i] !=0)\n \t{\n \t\tif (charArrS[s[i]] == 0 && charArrT[t[i]] == 0)\n \t\t{\n \t\t\tcharArrS[s[i]] = t[i];\n \t\t\tcharArrT[t[i]] = s[i];\n \t\t}\n \t\telse\n \t\tif (charArrS[s[i]] != t[i] || charArrT[t[i]] != s[i])\n \t\t\treturn false;\n \t\ti++;\n \t}\n \n \treturn true;\n }
78
0
[]
5
isomorphic-strings
8ms C++ Solution without Hashmap
8ms-c-solution-without-hashmap-by-xh2312-30de
bool isIsomorphic(string s, string t) {\n char map_s[128] = { 0 };\n char map_t[128] = { 0 };\n int len = s.size();\n
xh23123
NORMAL
2015-06-18T15:14:08+00:00
2018-08-12T19:23:52.860048+00:00
22,510
false
bool isIsomorphic(string s, string t) {\n char map_s[128] = { 0 };\n char map_t[128] = { 0 };\n int len = s.size();\n for (int i = 0; i < len; ++i)\n {\n if (map_s[s[i]]!=map_t[t[i]]) return false;\n map_s[s[i]] = i+1;\n map_t[t[i]] = i+1;\n }\n return true; \n }
75
6
['C++']
15
isomorphic-strings
[Python/C++] 2 solutions - Clean & Concise
pythonc-2-solutions-clean-concise-by-hie-16ia
\u2714\uFE0F Solution 1: Normalize 2 strings\n- The idea is to normalize s and t into the same string.\n- For example: s = "egg", t = "add"\n\t- Then both will
hiepit
NORMAL
2021-07-12T07:17:53.072729+00:00
2021-08-30T03:31:44.617203+00:00
4,619
false
**\u2714\uFE0F Solution 1: Normalize 2 strings**\n- The idea is to normalize `s` and `t` into the same string.\n- For example: `s = "egg", t = "add"`\n\t- Then both will be normalized as `"abb"`.\n- Finally, compare if the normalize version of 2 string is the same or not.\n\n**Python 3**\n```python\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n def normalize(s):\n seen = dict()\n ans = ""\n nextChr = \'a\'\n for c in s:\n if c not in seen:\n seen[c] = nextChr\n nextChr = chr(ord(nextChr) + 1)\n ans += seen[c]\n return ans\n\n return normalize(s) == normalize(t)\n```\n\n**C++**\n```\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n return normalize(s) == normalize(t);\n }\n string normalize(const string& s) {\n char mapping[128] = {};\n string ans = "";\n char nextChr = \'a\';\n for (char c : s) {\n if (mapping[c] == 0) {\n mapping[c] = nextChr;\n ++nextChr;\n }\n ans += mapping[c];\n }\n return ans;\n }\n};\n```\n\n**Complexity:**\n- Time: `O(N)`\n- Space: `O(N)`\n\n---\n\n**\u2714\uFE0F Solution 2: Using 2 dict**\n- The idea is to create 2 dicts: `sDict` and `tDict`, `sDict` map character in string `s` to coressponding character in string `t`, if later retrieving they are mismatch, we return False.\n- For example: `s = "ege", t = "add"`\n\t- At `i = 0`: `sDict{\'e\': \'a\'}, tDict{\'a\':\'e\'}`\n\t- At `i = 1`: `sDict{\'e\': \'a\', \'g\':\'d\'}, tDict{\'a\':\'e\', \'d\':\'g\'}`\n\t- At `i = 2`: `sDict[\'e\'] <> \'d\'` mismatched!! return False.\n\n**Python 3**\n```python\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n sDict = {}\n tDict = {}\n for c1, c2 in zip(s, t):\n # Case 1: No mapping exists in either of the dictionaries -> Let\'s mapping\n if (c1 not in sDict) and (c2 not in tDict):\n sDict[c1] = c2\n tDict[c2] = c1\n # Case 2: Case one side is mapped but the other is not. Or both mapping exists but they mismatch! \n elif (c1 not in sDict) or (c2 not in tDict) or (sDict[c1] != c2) or (tDict[c2] != c1):\n return False\n return True\n```\n**Complexity**\n- Time: `O(N)`\n- Space: `O(26)`, dict to store up to 26 different characters.
70
14
[]
8
isomorphic-strings
[JAVA] easy 4 liner solution
java-easy-4-liner-solution-by-jugantar20-uvsm
\n\n# Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity here, e.g. O(n) \n
Jugantar2020
NORMAL
2022-10-09T14:15:45.193168+00:00
2022-10-09T14:15:45.193408+00:00
9,591
false
\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public boolean isIsomorphic(String s, String t) {\n Map<Character, Integer> map1 = new HashMap<>();\n Map<Character, Integer> map2 = new HashMap<>();\n\n for(Integer i = 0; i <s.length(); i ++) {\n if(map1.put(s.charAt(i), i) != map2.put(t.charAt(i), i))\n return false;\n }\n return true;\n }\n}\n```\n# PLEASE UPVOTE IF IT WAS HELPFULL
62
1
['Java']
12
isomorphic-strings
✅5 Different types of solutions✅ || Brute Force ➡️Optimization || Easy To Understand✅
5-different-types-of-solutions-brute-for-tqd5
\n\n# Intuition\nGiven two strings, s and t, determine if they are isomorphic. Two strings are isomorphic if the characters in s can be mapped to the characters
Onkar-S
NORMAL
2023-12-04T13:14:24.569665+00:00
2023-12-04T13:14:24.569690+00:00
4,386
false
![upvote.jpeg](https://assets.leetcode.com/users/images/c0a8c580-c394-42f6-ba29-befa860f2e21_1701695449.1023154.jpeg)\n\n# Intuition\nGiven two strings, `s` and `t`, determine if they are isomorphic. Two strings are isomorphic if the characters in `s` can be mapped to the characters in `t` in a one-to-one relationship.\n\n## Approach 1\nThe provided C++ code uses a simple approach to determine if two strings are isomorphic. Here\'s a step-by-step explanation:\n\n1. **Length Check:**\n - Check if the lengths of strings `s` and `t` are equal. If not, return `false` because strings of different lengths cannot be isomorphic.\n\n2. **Initialize Data Structures:**\n - Create a vector `visited` of size 128, initialized to zeros. This vector is used to track the mapping of characters in string `s` to characters in string `t`.\n\n3. **Iterate Through Characters:**\n - Use a for loop to iterate through each character of the strings `s` and `t` simultaneously.\n - For each character at index `i`:\n - Retrieve the characters `charS` and `charT` from strings `s` and `t`, respectively.\n\n4. **Check Unvisited Character in `s`:**\n - If `visited[charS]` is zero, it means the character `charS` in string `s` is not mapped to any character in `t` yet.\n - Check if the corresponding character `charT` in string `t` has already been used as a mapping for another character in `s`.\n - If yes, return `false` because two characters in `s` cannot be mapped to the same character in `t`.\n - If no, establish a mapping by setting `visited[charS]` to `charT`.\n\n5. **Check Previously Visited Character in `s`:**\n - If `visited[charS]` is not zero, it means the character `charS` in string `s` has been mapped before.\n - Check if the current mapping is consistent with the character `charT` in string `t`.\n - If not consistent, return `false` because the strings are not isomorphic.\n\n6. **Return Result:**\n - After iterating through all characters, if no inconsistencies are found, return `true` indicating that the strings are isomorphic.\n\n## Complexity Analysis\n- **Time Complexity:** $$O(n^2)$$, where `n` is the length of the input strings. The time complexity is dominated by the `std::count` function, which has a time complexity of $$O(n)$$ and is called within the for loop.\n- **Space Complexity:** $$O(1)$$, as the space required is constant. The `visited` vector has a fixed size of 128, and the other variables used are of constant space.\n\nI appreciate your patience and diligence in clarifying the details. If you have any further questions or if there\'s anything else you\'d like to discuss, feel free to let me know!\n\n# Code\n```\n#include <vector>\n#include <string>\n\nclass Solution {\npublic:\n bool isIsomorphic(std::string s, std::string t) {\n if (s.length() != t.length()) {\n return false; // Different lengths cannot be isomorphic\n }\n\n std::vector<char> visited(128, 0); // Track characters visited in s\n\n for (int i = 0; i < s.length(); i++) {\n char charS = s[i];\n char charT = t[i];\n\n if (visited[charS] == 0) {\n // Check if the character in t has already been mapped\n if (std::count(visited.begin(), visited.end(), charT) > 0) {\n return false;\n }\n\n visited[charS] = charT; // Map the character in s to the character in t\n } else if (visited[charS] != charT) {\n return false;\n }\n }\n\n return true;\n }\n};\n\n```\n\n\n\n\n## Approach 2\nThe provided C++ code uses an optimized approach with two vectors, `lastPosS` and `lastPosT`, to track the last positions of characters in strings `s` and `t`, respectively. Here\'s a step-by-step explanation:\n\n1. **Length Check:**\n - Check if the lengths of strings `s` and `t` are equal. If not, return `false` because strings of different lengths cannot be isomorphic.\n\n2. **Initialize Data Structures:**\n - Create two vectors, `lastPosS` and `lastPosT`, each of size 256, initialized to -1. These vectors are used to track the last positions of characters in strings `s` and `t`.\n\n3. **Iterate Through Characters:**\n - Use a for loop to iterate through each character of the strings `s` and `t` simultaneously.\n - For each character at index `i`:\n - Retrieve the characters `charS` and `charT` from strings `s` and `t`, respectively.\n\n4. **Check Last Positions:**\n - Compare the last positions of `charS` in string `s` (`lastPosS[charS]`) and `charT` in string `t` (`lastPosT[charT]`).\n - If the last positions are not equal, return `false` because the strings are not isomorphic.\n - If the last positions are equal, continue to the next iteration.\n\n5. **Update Last Positions:**\n - Update the last positions of `charS` in `lastPosS` and `charT` in `lastPosT` to the current index `i`.\n\n6. **Return Result:**\n - After iterating through all characters, return `true` indicating that the strings are isomorphic.\n\n## Complexity Analysis\n- **Time Complexity:** $$O(n)$$, where `n` is the length of the input strings. The algorithm iterates through each character in the strings once, and the operations inside the loop are constant time.\n- **Space Complexity:** $$O(1)$$, as the space required is constant. The vectors `lastPosS` and `lastPosT` have fixed sizes of 256.\n\nThis optimized approach reduces the time complexity compared to the previous implementation by avoiding the use of `std::count`.\n```\n#include <vector>\n#include <string>\n\nclass Solution {\npublic:\n bool isIsomorphic(std::string s, std::string t) {\n if (s.length() != t.length()) {\n return false; // Different lengths cannot be isomorphic\n }\n\n std::vector<int> lastPosS(256, -1); // Track last position of characters in s\n std::vector<int> lastPosT(256, -1); // Track last position of characters in t\n\n for (int i = 0; i < s.length(); i++) {\n char charS = s[i];\n char charT = t[i];\n\n if (lastPosS[charS] != lastPosT[charT]) {\n return false;\n }\n\n // Update the last positions\n lastPosS[charS] = i;\n lastPosT[charT] = i;\n }\n\n return true;\n }\n};\n\n```\n\n\n\nGiven two strings, `s` and `t`, determine if they are isomorphic. Two strings are isomorphic if the characters in `s` can be mapped to the characters in `t` in a one-to-one relationship.\n\n## Approach 3\nThe provided C++ code uses two arrays, `map_s` and `map_t`, to track the mapping of characters in strings `s` and `t`. Here\'s a step-by-step explanation:\n\n1. **Initialize Arrays:**\n - Create two arrays, `map_s` and `map_t`, each of size 128, initialized to 0. These arrays are used to map characters in strings `s` and `t`.\n\n2. **Iterate Through Characters:**\n - Use a for loop to iterate through each character of the strings `s` and `t` simultaneously.\n - For each character at index `i`:\n - Check if the mapping of `s[i]` in `map_s` is not equal to the mapping of `t[i]` in `map_t`.\n - If not equal, return `false` because the strings are not isomorphic.\n - If equal, continue to the next iteration.\n\n3. **Update Mappings:**\n - Update the mappings by setting `map_s[s[i]]` and `map_t[t[i]]` to `i + 1`. The addition of 1 is used to differentiate from the default initialization value (0).\n\n4. **Return Result:**\n - After iterating through all characters, return `true` indicating that the strings are isomorphic.\n\n## Complexity Analysis\n- **Time Complexity:** $$O(n)$$, where `n` is the length of the input strings. The algorithm iterates through each character in the strings once, and the operations inside the loop are constant time.\n- **Space Complexity:** $$O(1)$$, as the space required is constant. The arrays `map_s` and `map_t` have fixed sizes of 128.\n\nThis approach uses arrays to directly map characters to their positions in the strings, simplifying the tracking of isomorphism. \n\n```\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n char map_s[128] = { 0 };\n char map_t[128] = { 0 };\n int len = s.size();\n for (int i = 0; i < len; ++i)\n {\n if (map_s[s[i]]!=map_t[t[i]]) return false;\n map_s[s[i]] = i+1;\n map_t[t[i]] = i+1;\n }\n return true; \n }\n};\n```\n\n\n## Approach 4\nThe provided C++ code uses unordered maps, `mp1` and `mp2`, to store the positions of characters in strings `s` and `t`, respectively. Here\'s a step-by-step explanation:\n\n1. **Initialize Unordered Maps:**\n - Create two unordered maps, `mp1` and `mp2`, where the keys are characters, and the values are vectors of integers representing the positions of the characters in the strings.\n\n2. **Length Check:**\n - Check if the lengths of strings `s` and `t` are equal. If not, return `false` because strings of different lengths cannot be isomorphic.\n\n3. **Map Positions in `s` and `t`:**\n - Use a for loop to iterate through each character of the strings `s` and `t` simultaneously.\n - For each character at index `i`:\n - Push the position `i` into the vector associated with the character `s[i]` in `mp1`.\n - Push the position `i` into the vector associated with the character `t[i]` in `mp2`.\n\n4. **Check Mappings:**\n - Use another for loop to iterate through each character of the strings `s` and `t` simultaneously.\n - For each character at index `i`:\n - Check if the vectors associated with `s[i]` in `mp1` and `t[i]` in `mp2` are equal.\n - If not equal, return `false` because the strings are not isomorphic.\n\n5. **Return Result:**\n - After iterating through all characters, return `true` indicating that the strings are isomorphic.\n\n## Complexity Analysis\n- **Time Complexity:** $$O(n)$$, where `n` is the length of the input strings. The algorithm iterates through each character in the strings once, and the operations inside the loops are constant time.\n- **Space Complexity:** $$O(m)$$, where `m` is the number of unique characters in the input strings. In the worst case, each character contributes to the unordered maps, resulting in a space complexity proportional to the number of unique characters.\n\nThis approach efficiently uses unordered maps to track positions and compare mappings for isomorphism.\n```\n\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n unordered_map<char,vector<int>>mp1,mp2;\n if(s.length()!=t.length())return false;\n for(int i=0;i<s.length();i++ )\n {\n mp1[s[i]].push_back(i);\n }\n for(int i=0;i<t.length();i++ )\n {\n mp2[t[i]].push_back(i);\n }\n for (int i = 0; i < s.length(); i++) {\n if (mp1[s[i]] != mp2[t[i]]) {\n return false;\n }\n }\n\n return true;\n }\n};\n\n```\n\n\n## Approach 5\nThe provided C++ code uses an unordered map (`charMap`) and an unordered set (`usedChars`) to track the mapping of characters in string `s` to characters in string `t`. Here\'s a step-by-step explanation:\n\n1. **Initialization:**\n - Initialize the size `n` as the length of string `s`.\n - Create an unordered map `charMap` to store the mapping of characters from `s` to `t`.\n - Create an unordered set `usedChars` to keep track of characters from `t` that have been used in the mapping.\n\n2. **Iterate Through Characters:**\n - Use a for loop to iterate through each character of the strings `s` and `t` simultaneously.\n - For each character at index `i`:\n - Check if the character `s[i]` is not in `charMap` and the corresponding character `t[i]` is not in `usedChars`.\n - If true, establish a mapping by adding `s[i] -> t[i]` in `charMap` and insert `t[i]` into `usedChars`.\n - If false, check the consistency of the mapping:\n - If `s[i]` is not in `charMap`, but `t[i]` is already in `usedChars`, return `false` because two characters in `s` cannot be mapped to the same character in `t`.\n - If `s[i]` is in `charMap`, but the mapped character is not equal to `t[i]`, return `false` because the mapping is not consistent.\n\n3. **Return Result:**\n - After iterating through all characters, return `true` indicating that the strings are isomorphic.\n\n## Complexity Analysis\n- **Time Complexity:** $$O(n)$$, where `n` is the length of the input strings. The algorithm iterates through each character in the strings once, and the operations inside the loop are constant time.\n- **Space Complexity:** $$O(m)$$, where `m` is the number of unique characters in the input strings. In the worst case, each character contributes to the unordered map and set, resulting in a space complexity proportional to the number of unique characters.\n\nThis approach efficiently uses an unordered map and set to track the mapping of characters and ensure consistency for isomorphism. \n```\n\nclass Solution {\npublic:\n bool isIsomorphic(std::string s, std::string t) {\n int n = s.size();\n std::unordered_map<char, char> charMap;\n std::unordered_set<char> usedChars;\n\n for (int i = 0; i < n; i++) {\n if (charMap.count(s[i]) == 0 && usedChars.count(t[i]) == 0) {\n charMap[s[i]] = t[i];\n usedChars.insert(t[i]);\n } else if (charMap.count(s[i]) == 0 && usedChars.count(t[i])) {\n return false;\n } else if (charMap[s[i]] != t[i]) {\n return false;\n }\n }\n\n return true;\n }\n};\n```\n![upvote.jpeg](https://assets.leetcode.com/users/images/63e21bc3-a9b5-4819-af95-134bbb67301e_1701695423.7912824.jpeg)\n
55
0
['Array', 'Hash Table', 'String', 'C++']
6
isomorphic-strings
Java 3ms beats 99.25%
java-3ms-beats-9925-by-joebluesky-v3t1
Since all the test cases use ASCII characters, you can use small arrays as a lookup tables.\n\n public class Solution {\n \n public boolean isI
joebluesky
NORMAL
2016-04-02T06:04:58+00:00
2016-04-02T06:04:58+00:00
13,848
false
Since all the test cases use ASCII characters, you can use small arrays as a lookup tables.\n\n public class Solution {\n \n public boolean isIsomorphic(String sString, String tString) {\n \n char[] s = sString.toCharArray();\n char[] t = tString.toCharArray();\n \n int length = s.length;\n if(length != t.length) return false;\n \n char[] sm = new char[256];\n char[] tm = new char[256];\n \n for(int i=0; i<length; i++){\n char sc = s[i];\n char tc = t[i];\n if(sm[sc] == 0 && tm[tc] == 0){\n sm[sc] = tc;\n tm[tc] = sc;\n }else{\n if(sm[sc] != tc || tm[tc] != sc){\n return false;\n }\n }\n }\n return true;\n }\n }
52
0
['Java']
13
isomorphic-strings
1 line Python Solution, 95%
1-line-python-solution-95-by-antarestsao-a2pk
Say we have 2 strings 'add' and 'egg':\nfor the result to be true, one letter in the first string must have an unique mapping to one letter in the other string.
antarestsao
NORMAL
2016-10-30T21:25:24.663000+00:00
2018-10-16T00:54:02.653681+00:00
3,861
false
Say we have 2 strings ```'add'``` and ```'egg'```:\nfor the result to be true, one letter in the first string must have an unique mapping to one letter in the other string. \n```'a'->'e'``` and ```'d'->'g'```\nAnd the number of such mapping should be the **SAME** as the number of different letters in the 2 strings. \nAnd that is all we need to check.\n\n```\nclass Solution(object):\n def isIsomorphic(self, s, t):\n """\n :type s: str\n :type t: str\n :rtype: bool\n """\n return len(set(s)) == len(set(zip(s, t))) == len(set(t))\n```
50
1
[]
5
isomorphic-strings
🔥🔥🔥🔥🔥 Beat 99% 🔥🔥🔥🔥🔥 EASY 🔥🔥🔥🔥🔥🔥
beat-99-easy-by-abdallaellaithy-re8w
\n\n\n# Code\n\nclass Solution(object):\n def isIsomorphic(self, s, t):\n """\n :type s: str\n :type t: str\n :rtype: bool\n
abdallaellaithy
NORMAL
2024-04-02T00:02:24.653648+00:00
2024-04-02T00:05:11.565839+00:00
16,169
false
[![1.png](https://assets.leetcode.com/users/images/cb7d4f5c-e606-456f-ad90-b86e69030c0f_1712016299.7372751.png)](https://leetcode.com/problems/isomorphic-strings/submissions/1203909730/?envType=daily-question&envId=2024-04-02)\n\n\n# Code\n```\nclass Solution(object):\n def isIsomorphic(self, s, t):\n """\n :type s: str\n :type t: str\n :rtype: bool\n """\n return len(set(zip(s,t))) == len(set(s)) == len(set(t))\n```
47
0
['String', 'Python', 'Python3']
11
isomorphic-strings
Javascript 6 lines solution
javascript-6-lines-solution-by-lostrace-yfri
var isIsomorphic = function(s, t) {\n var obj = {};\n \n for(var i = 0; i < s.length; i++){\n if(!obj['s' + s[i]]) obj['s' + s[i]] =
lostrace
NORMAL
2015-09-10T17:10:00+00:00
2015-09-10T17:10:00+00:00
7,145
false
var isIsomorphic = function(s, t) {\n var obj = {};\n \n for(var i = 0; i < s.length; i++){\n if(!obj['s' + s[i]]) obj['s' + s[i]] = t[i];\n if(!obj['t' + t[i]]) obj['t' + t[i]] = s[i];\n if(t[i] != obj['s' + s[i]] || s[i] != obj['t' + t[i]]) return false;\n }\n return true;\n };
42
2
['JavaScript']
5
isomorphic-strings
5 lines simple Java
5-lines-simple-java-by-stefanpochmann-mm4d
public boolean isIsomorphic(String s, String t) {\n Map m = new HashMap();\n for (Integer i=0; i<s.length(); ++i)\n if (m.put(s.charAt(
stefanpochmann
NORMAL
2016-01-17T15:44:56+00:00
2018-08-24T12:29:44.554517+00:00
15,485
false
public boolean isIsomorphic(String s, String t) {\n Map m = new HashMap();\n for (Integer i=0; i<s.length(); ++i)\n if (m.put(s.charAt(i), i) != m.put(t.charAt(i)+"", i))\n return false;\n return true;\n }\n\nBased on my [earlier solution for another problem](https://leetcode.com/discuss/62374/8-lines-simple-java). There I was matching chars and strings, which allowed me to use the same map for both. Here I only have chars, so I turn the chars from `t` into strings.
39
7
['Java']
20
isomorphic-strings
JS hashmap solution
js-hashmap-solution-by-yushi_lu-f28w
We use a Map to record the key/val pair in S and T. For each char in S, if we never met it before, we record the (s[i], t[i]) pair in map. If we met s[i] before
yushi_lu
NORMAL
2019-07-28T01:28:09.142443+00:00
2019-07-28T01:28:09.142474+00:00
4,993
false
We use a Map to record the key/val pair in S and T. For each char in S, if we never met it before, we record the (s[i], t[i]) pair in map. If we met s[i] before, we compare the value of s[i] with t[i], which are supposed to be the same. After that, we need to check whether map.values() contain duplicate value. If map.value contain duplicate value, it means that multiple keys map to a same value, which is not allowed. To illustrate,\n```\ns = "abc"\nt = "aaa"\nMap("a" => "a", "b" => "a", "c" => "a")\n```\nThe above strings are not *isomorphic.*\n```\nvar isIsomorphic = function(s, t) {\n if (s.length != t.length)\n return false\n let m = new Map()\n for (let i = 0; i < s.length; i++) {\n if (!m.has(s[i]))\n m.set(s[i], t[i])\n else {\n \n if (m.get(s[i]) != t[i]) {\n \n return false\n }\n }\n }\n return new Set([...m.values()]).size == m.size\n \n};\n```
36
0
['JavaScript']
3
isomorphic-strings
✅Accepted || ✅Short & Simple || ✅Best Method || ✅Easy-To-Understand
accepted-short-simple-best-method-easy-t-6x26
\n# Code\n\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n int m1[256] = {0}, m2[256] = {0}, n = s.size();\n for (int i
sanjaydwk8
NORMAL
2023-01-30T08:37:37.890470+00:00
2023-01-30T08:37:37.890507+00:00
7,388
false
\n# Code\n```\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n int m1[256] = {0}, m2[256] = {0}, n = s.size();\n for (int i = 0; i < n; ++i) {\n if (m1[s[i]] != m2[t[i]]) return false;\n m1[s[i]] = i + 1;\n m2[t[i]] = i + 1;\n }\n return true;\n }\n};\n```\nPlease **UPVOTE** if it helps \u2764\uFE0F\uD83D\uDE0A\nThank You and Happy To Help You!!
29
0
['C++']
4
isomorphic-strings
[Python] Easy Approach ✔
python-easy-approach-by-triposat-bi4i
\tclass Solution:\n\t\tdef isIsomorphic(self, s: str, t: str) -> bool:\n\t\t\tif len(set(s)) != len(set(t)):\n\t\t\t\treturn False\n\t\t\thash_map = {}\n\t\t\tf
triposat
NORMAL
2022-01-17T10:08:37.823649+00:00
2022-04-27T12:43:47.027250+00:00
4,692
false
\tclass Solution:\n\t\tdef isIsomorphic(self, s: str, t: str) -> bool:\n\t\t\tif len(set(s)) != len(set(t)):\n\t\t\t\treturn False\n\t\t\thash_map = {}\n\t\t\tfor char in range(len(t)):\n\t\t\t\tif t[char] not in hash_map:\n\t\t\t\t\thash_map[t[char]] = s[char]\n\t\t\t\telif hash_map[t[char]] != s[char]:\n\t\t\t\t\treturn False\n\t\t\treturn True
28
1
['Python', 'Python3']
5
isomorphic-strings
Intuitive ➡️ Explained In Depth ➡️[Java/C++/JavaScript/C#/Python3/Go]
intuitive-explained-in-depth-javacjavasc-ev04
Approach\n1. Initialize Frequency Maps: Two arrays, map1 and map2, of size 128 are created. These arrays are used to store the frequency of characters encounter
Shivansu_7
NORMAL
2024-04-02T03:50:27.251785+00:00
2024-04-02T03:50:27.251814+00:00
3,324
false
# Approach\n1. **Initialize Frequency Maps**: Two arrays, `map1` and `map2`, of size 128 are created. These arrays are used to store the frequency of characters encountered in strings `s` and `t`, respectively. Since the ASCII character set has 128 characters, these arrays can efficiently store the frequency of each character encountered.\n\n2. **Iterate Through Characters**: The code iterates through each character of the strings `s` and `t` simultaneously using a single loop. For each character at position `i`, it retrieves the characters `s_ch` and `t_ch`.\n\n3. **Mapping Characters**: \n - If both `s_ch` and `t_ch` haven\'t been encountered before (`map1[s_ch] == 0 && map2[t_ch] == 0`), it establishes a mapping between them. It sets `map1[s_ch]` to `t_ch` and `map2[t_ch]` to `s_ch`.\n - If there\'s already a mapping but it doesn\'t match the current characters, it means the strings are not isomorphic, so it returns `false`.\n\n4. **Return**: After iterating through all characters, if no inconsistency is found, it returns `true`, indicating that the strings are isomorphic.\n\n***This approach effectively determines if the given strings `s` and `t` are isomorphic by ensuring that each character in one string uniquely maps to a character in the other string, and vice versa, maintaining the isomorphism property. The use of frequency maps allows for efficient tracking of character mappings.***\n\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```Java []\nclass Solution {\n public boolean isIsomorphic(String s, String t) {\n int[] map1 = new int[128]; // Stores frequency of s\n int[] map2 = new int[128]; // Stores frequency of t\n\n for(int i=0; i<s.length(); i++) {\n char s_ch = s.charAt(i);\n char t_ch = t.charAt(i);\n\n if(map1[s_ch]==0 && map2[t_ch]==0) {\n map1[s_ch] = t_ch;\n map2[t_ch] = s_ch;\n }\n else if(map1[s_ch] != t_ch || map2[t_ch] != s_ch) {\n return false;\n }\n }\n return true;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n vector<int> map1(128, 0); // Stores frequency of s\n vector<int> map2(128, 0); // Stores frequency of t\n\n for(int i=0; i<s.length(); i++) {\n char s_ch = s[i];\n char t_ch = t[i];\n\n if(map1[s_ch]==0 && map2[t_ch]==0) {\n map1[s_ch] = t_ch;\n map2[t_ch] = s_ch;\n }\n else if(map1[s_ch] != t_ch || map2[t_ch] != s_ch) {\n return false;\n }\n }\n return true;\n }\n};\n```\n```Python3 []\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n map1 = [0] * 128 # Stores frequency of s\n map2 = [0] * 128 # Stores frequency of t\n\n for i in range(len(s)):\n s_ch = s[i]\n t_ch = t[i]\n\n if map1[ord(s_ch)] == 0 and map2[ord(t_ch)] == 0:\n map1[ord(s_ch)] = ord(t_ch)\n map2[ord(t_ch)] = ord(s_ch)\n elif map1[ord(s_ch)] != ord(t_ch) or map2[ord(t_ch)] != ord(s_ch):\n return False\n return True\n```\n```C# []\npublic class Solution {\n public bool IsIsomorphic(string s, string t) {\n int[] map1 = new int[128]; // Stores frequency of s\n int[] map2 = new int[128]; // Stores frequency of t\n\n for(int i=0; i<s.Length; i++) {\n char s_ch = s[i];\n char t_ch = t[i];\n\n if(map1[s_ch]==0 && map2[t_ch]==0) {\n map1[s_ch] = t_ch;\n map2[t_ch] = s_ch;\n }\n else if(map1[s_ch] != t_ch || map2[t_ch] != s_ch) {\n return false;\n }\n }\n return true;\n }\n}\n```\n```Go []\nfunc isIsomorphic(s string, t string) bool {\n map1 := make([]int, 128) // Stores frequency of s\n map2 := make([]int, 128) // Stores frequency of t\n\n for i := 0; i < len(s); i++ {\n sCh := s[i]\n tCh := t[i]\n\n if map1[sCh] == 0 && map2[tCh] == 0 {\n map1[sCh] = int(tCh)\n map2[tCh] = int(sCh)\n } else if map1[sCh] != int(tCh) || map2[tCh] != int(sCh) {\n return false\n }\n }\n return true\n}\n```\n```Rust []\nimpl Solution {\n pub fn is_isomorphic(s: String, t: String) -> bool {\n let mut map1 = vec![0; 128]; // Stores frequency of s\n let mut map2 = vec![0; 128]; // Stores frequency of t\n\n for (s_ch, t_ch) in s.chars().zip(t.chars()) {\n if map1[s_ch as usize] == 0 && map2[t_ch as usize] == 0 {\n map1[s_ch as usize] = t_ch as i32;\n map2[t_ch as usize] = s_ch as i32;\n } else if map1[s_ch as usize] != t_ch as i32 || map2[t_ch as usize] != s_ch as i32 {\n return false;\n }\n }\n true\n }\n}\n```\n```JavaScript []\n/**\n * @param {string} s\n * @param {string} t\n * @return {boolean}\n */\nvar isIsomorphic = function(s, t) {\n let map1 = new Array(128).fill(0); // Stores frequency of s\n let map2 = new Array(128).fill(0); // Stores frequency of t\n\n for (let i = 0; i < s.length; i++) {\n let sCh = s.charCodeAt(i);\n let tCh = t.charCodeAt(i);\n\n if (map1[sCh] === 0 && map2[tCh] === 0) {\n map1[sCh] = tCh;\n map2[tCh] = sCh;\n } else if (map1[sCh] !== tCh || map2[tCh] !== sCh) {\n return false;\n }\n }\n return true;\n};\n```\n\n---\n\n\n---\n\n![5c63d377-8ef4-4beb-b09d-0edb07e09a41_1702955205.6568592.png](https://assets.leetcode.com/users/images/166c37fd-e52b-400b-bcf4-b8be648998df_1712029752.3208227.png)\n
26
0
['Python', 'C++', 'Java', 'Go', 'Python3', 'Rust', 'JavaScript', 'C#']
4
isomorphic-strings
Java ☕| With/without Hashmap ✅✅| Dry run examples 🚀| Handwritten Notes 🎯| Beginners Friendly ✔️✔️
java-withwithout-hashmap-dry-run-example-zxea
Intuition\nThe problem requires determining whether two strings are isomorphic. The main idea is to establish a one-to-one mapping between characters in both st
pnkulkarni05
NORMAL
2024-04-02T03:43:08.797492+00:00
2024-04-02T05:28:21.549347+00:00
2,779
false
# Intuition\nThe problem requires determining whether two strings are isomorphic. The main idea is to establish a one-to-one mapping between characters in both strings.\n\n# Approach 1: Using HashMap\nIn this approach, we use two hashmaps to store mappings between characters of both strings. We iterate through each character of the strings, updating the mappings in the hashmaps. If at any point we find an inconsistency, we return false.\n\n# Complexity\n- Time complexity: $$O(n)$$, where $$n$$ is the length of the input strings.\n- Space complexity: $$O(1)$$, as the space used remains constant.\n\n# Dry Run\n\n![WhatsApp Image 2024-04-02 at 9.02.36 AM.jpeg](https://assets.leetcode.com/users/images/1fb24b48-b6df-46ee-8fb8-0d9afe916af9_1712028783.8634012.jpeg)\n\n![WhatsApp Image 2024-04-02 at 8.49.28 AM.jpeg](https://assets.leetcode.com/users/images/567891f6-1215-40a0-8a0c-e76b506866c7_1712028802.172942.jpeg)\n\n\n\n\n\n# Code\n\n``` java []\nimport java.util.HashMap;\n\nclass Solution {\n public boolean isIsomorphic(String s, String t) {\n if (s.length() != t.length()) {\n return false;\n }\n \n HashMap<Character, Character> map = new HashMap<>();\n HashMap<Character, Character> reverseMap = new HashMap<>();\n \n for (int i = 0; i < s.length(); i++) {\n char charS = s.charAt(i);\n char charT = t.charAt(i);\n \n if (map.containsKey(charS)) {\n if (map.get(charS) != charT) {\n return false;\n }\n } else {\n if (reverseMap.containsKey(charT)) {\n return false;\n }\n map.put(charS, charT);\n reverseMap.put(charT, charS);\n }\n }\n \n return true;\n }\n}\n```\n\n---\n\n\n# Approach 2: Using Array\nIn this approach, we use two arrays to store mappings between characters of both strings. We iterate through each character of the strings, updating the mappings in both arrays. If at any point we find an inconsistency, we return false.\n\n# Complexity\n- Time complexity: $$O(n)$$, where $$n$$ is the length of the input strings.\n- Space complexity: $$O(1)$$, as we use fixed-size arrays.\n\n\n# Dry Run\n\n![WhatsApp Image 2024-04-02 at 8.48.46 AM.jpeg](https://assets.leetcode.com/users/images/d2486497-de68-41bb-beb1-a72fa88a8e1b_1712028622.3579848.jpeg)\n\n\n# Code \n``` java []\nclass Solution {\n public boolean isIsomorphic(String s, String t) {\n if (s.length() != t.length()) {\n return false;\n }\n \n char[] sToTMapping = new char[128];\n char[] tToSMapping = new char[128];\n \n for (int i = 0; i < s.length(); i++) {\n char charS = s.charAt(i);\n char charT = t.charAt(i);\n \n if (sToTMapping[charS] == 0 && tToSMapping[charT] == 0) {\n sToTMapping[charS] = charT;\n tToSMapping[charT] = charS;\n } else if (sToTMapping[charS] != charT || tToSMapping[charT] != charS) {\n return false;\n }\n }\n \n return true;\n }\n}\n\n```\n\n---\n\n\n\n\n\n![_26aa17f5-1f66-45b1-93ed-9e9a5eba2370.jpg](https://assets.leetcode.com/users/images/777cec03-c45a-494a-b297-8df1dcb92af3_1712028874.470021.jpeg)\n\n\n\n---\n# My Solutions:\n\n\uD83D\uDFE0 - easy\n\u26AA - medium\n\uD83D\uDFE2 - hard\n\n\n\n\n[\uD83D\uDFE0 2485. Find the Pivot Integer](https://leetcode.com/problems/find-the-pivot-integer/solutions/4866556/java-1-ms-2-different-approaches-easy-to-understand)\n[\u26AA 1171. Remove Zero Sum Consecutive Nodes from Linked List](https://leetcode.com/problems/remove-zero-sum-consecutive-nodes-from-linked-list/solutions/4862243/java-2ms-hashmap-beats-8913-users-with-java-easy-to-understand-dry-run)\n[\u26AA 791. Custom Sort String](https://leetcode.com/problems/custom-sort-string/solutions/4856517/hashmap-java-2-ms-easy-to-understand-unique-approach-dry-run-with-examples)\n[\uD83D\uDFE0 349. Intersection of Two Arrays](https://leetcode.com/problems/intersection-of-two-arrays/solutions/4851592/3-different-approaches-java-hashset-two-pointer-sorting-beats-9383-memory)\n[\uD83D\uDFE0 2540. Minimum Common Value](https://leetcode.com/problems/minimum-common-value/solutions/4845131/2-different-approaches-java-easy-to-understand-beginners-friendly-different-but-easy)\n[\uD83D\uDFE0 3005. Count Elements With Maximum Frequency](https://leetcode.com/problems/count-elements-with-maximum-frequency/solutions/4840029/discussed-2-approaches-java-beginner-friendly-easy-to-understand-withwithout-hashmap)\n[\uD83D\uDFE0 1678. Goal Parser Interpretation](https://leetcode.com/problems/goal-parser-interpretation/solutions/4836284/java-unique-approach-stringbuilder-0-ms-something-different-beginner-friendly)\n[\uD83D\uDFE0 1108. Defanging an IP Address](https://leetcode.com/problems/defanging-an-ip-address/solutions/4826558/single-line-java-solution-beats-100-java-users-0-ms-replace-method)\n[\u26AA 948. Bag of Tokens](https://leetcode.com/problems/bag-of-tokens/solutions/4820024/easy-explanation-two-pointer-all-corner-cases-covered-beats-9713-java-users)\n[\u26AA 19. Remove Nth Node From End of List](https://leetcode.com/problems/remove-nth-node-from-end-of-list/solutions/4814427/java-solution-two-pointer-beats-100-java-users-0-ms-easy-explanation)\n[\u26AA 238. Product of Array Except Self](https://leetcode.com/problems/product-of-array-except-self/solutions/4794294/java-on-brute-force-breakdown-optimization-unveiled-step-by-step-simplification-must-read)\n[\u26AA 53. Maximum Subarray](https://leetcode.com/problems/maximum-subarray/solutions/4774598/max-subarray-sum-kadanes-algorithm-handwritten-notes-2-ms-java-beginner-friendly-solution)\n[\uD83D\uDFE2 42. Trapping Rain Water](https://leetcode.com/problems/trapping-rain-water/solutions/4774421/trapping-rainwater-on-handwritten-notes-java-1-ms-easy-for-beginners)\n[\uD83D\uDFE0 2121. Best Time to Buy and Sell Stock](https://leetcode.com/problems/best-time-to-buy-and-sell-stock/solutions/4774485/buy-sell-stocks-java-1-ms-handwritten-notes-beginners-friendly-solution-easy-explanation)\n[\uD83D\uDFE0 2859. Sum of Values at Indices With K Set Bits](https://leetcode.com/problems/sum-of-values-at-indices-with-k-set-bits/solutions/4655414/easy-to-understand-java-code-for-beginners-bit-manipulation-2ms-java-beginners-friendly)\n[\uD83D\uDFE0 1929. Concatenation of Array](https://leetcode.com/problems/concatenation-of-array/solutions/4590814/concantenation-of-array-java-easy-approache)\n[More..](https://leetcode.com/pnkulkarni05/)\n\n\n\n\n
24
0
['Array', 'Hash Table', 'String', 'Java']
9
isomorphic-strings
✅ 🔥 0 ms Runtime Beats 100% User🔥|| Code Idea ✅ || Algorithm & Solving Step ✅ ||
0-ms-runtime-beats-100-user-code-idea-al-47qv
\n\n\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE AT THE END \u2705 :\n\n### Approach: Using Array as Mapping Table for ASCII Characters :\n\n### Intuition\
Letssoumen
NORMAL
2024-12-04T00:48:32.455495+00:00
2024-12-04T00:48:32.455521+00:00
3,959
false
![Screenshot 2024-12-04 at 6.13.30\u202FAM.png](https://assets.leetcode.com/users/images/18575640-b60e-4810-ab82-c3477a786839_1733273101.8268774.png)\n\n\u2705 IF YOU LIKE THIS SOLUTION, PLEASE UPVOTE AT THE END \u2705 :\n\n### Approach: Using Array as Mapping Table for ASCII Characters :\n\n### **Intuition**\nInstead of using hash maps, we can leverage the fact that both `s` and `t` consist of valid ASCII characters (0\u2013255). This allows us to use two arrays of size 256 to track mappings between characters. Using arrays instead of hash maps simplifies the process, reduces overhead, and improves performance.\n\n### **Code Idea** :\n- Use two arrays (`mapST` and `mapTS`) of size 256 to track mappings from `s` to `t` and `t` to `s`.\n- Initialize each array with `-1` to indicate no mappings.\n- Iterate over the characters of `s` and `t`. Check and establish consistent mappings using the arrays.\n- If a conflict is detected (inconsistent mappings), return `false`. Otherwise, return `true`.\n\n---\n# Algorithm :\n1. **Initialization**:\n - Create two arrays `mapST[256]` and `mapTS[256]` initialized to `-1`.\n2. **Iteration**:\n - For each character pair \\( (s[i], t[i]) \\):\n - If `mapST[s[i]]` is not `-1` and `mapST[s[i]]` is not equal to `t[i]`, return `false`.\n - If `mapTS[t[i]]` is not `-1` and `mapTS[t[i]]` is not equal to `s[i]`, return `false`.\n - Otherwise, establish the mapping `mapST[s[i]] = t[i]` and `mapTS[t[i]] = s[i]`.\n3. **Return**:\n - If no conflicts are found, return `true`.\n\n---\n\n### **C++ Implementation** :\n\n```cpp\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n if (s.length() != t.length()) return false;\n \n int mapST[256], mapTS[256];\n fill(begin(mapST), end(mapST), -1);\n fill(begin(mapTS), end(mapTS), -1);\n \n for (int i = 0; i < s.length(); i++) {\n char chS = s[i], chT = t[i];\n \n if (mapST[chS] == -1 && mapTS[chT] == -1) {\n mapST[chS] = chT;\n mapTS[chT] = chS;\n } else {\n if (mapST[chS] != chT || mapTS[chT] != chS) {\n return false;\n }\n }\n }\n return true;\n }\n};\n```\n\n---\n\n### **Java Implementation** :\n\n```java\nclass Solution {\n public boolean isIsomorphic(String s, String t) {\n if (s.length() != t.length()) return false;\n \n int[] mapST = new int[256];\n int[] mapTS = new int[256];\n Arrays.fill(mapST, -1);\n Arrays.fill(mapTS, -1);\n \n for (int i = 0; i < s.length(); i++) {\n char chS = s.charAt(i);\n char chT = t.charAt(i);\n \n if (mapST[chS] == -1 && mapTS[chT] == -1) {\n mapST[chS] = chT;\n mapTS[chT] = chS;\n } else {\n if (mapST[chS] != chT || mapTS[chT] != chS) {\n return false;\n }\n }\n }\n return true;\n }\n}\n```\n\n---\n\n### **Python 3 Implementation** :\n\n```python\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n if len(s) != len(t):\n return False\n \n mapST = [-1] * 256\n mapTS = [-1] * 256\n \n for chS, chT in zip(s, t):\n if mapST[ord(chS)] == -1 and mapTS[ord(chT)] == -1:\n mapST[ord(chS)] = ord(chT)\n mapTS[ord(chT)] = ord(chS)\n elif mapST[ord(chS)] != ord(chT) or mapTS[ord(chT)] != ord(chS):\n return False\n \n return True\n```\n\n---\n\n### **Complexity Analysis** :\n\n- **Time Complexity**: O(n)\n - We traverse both strings in a single pass, where n is the length of the strings.\n \n- **Space Complexity**: O(1)\n - Two fixed-size arrays of 256 elements are used regardless of the input size, which is constant.\n\n---\n\n### **Explanation of Logic**\n1. **Mapping via Arrays**: \n - The ASCII values of characters are directly used as indices in the mapping arrays.\n - `mapST[chS]` stores what `chS` in `s` maps to in `t`.\n - `mapTS[chT]` stores what `chT` in `t` maps to in `s`.\n2. **Conflict Detection**:\n - If any inconsistency is found during the mappings, we immediately return `false`.\n - If all mappings are consistent, return `true`.\n\n---\n\n### **Advantages of This Approach**\n- **Efficient**: Using arrays instead of hash maps reduces time complexity in practice because array lookups are faster than hash table lookups.\n- **Memory Efficiency**: The solution uses a fixed amount of memory, making it suitable for large inputs.\n\n![image.png](https://assets.leetcode.com/users/images/159110b8-697a-4f1f-aaf5-530a3d00fdcd_1733273299.3073728.png)\n\n
23
0
['Hash Table', 'String', 'C++', 'Java', 'Python3']
1
isomorphic-strings
4ms Accept C code
4ms-accept-c-code-by-haiyuanli-yns5
Hopefully a nice balance of readability and performance.\n\nThe Code:\n\n bool isIsomorphic(char s, char t) {\n \t\tchar mapST[128] = { 0 };\n \t\tchar
haiyuanli
NORMAL
2015-05-14T05:36:25+00:00
2015-05-14T05:36:25+00:00
2,563
false
Hopefully a nice balance of readability and performance.\n\nThe Code:\n\n bool isIsomorphic(char* s, char* t) {\n \t\tchar mapST[128] = { 0 };\n \t\tchar mapTS[128] = { 0 };\n \t\tsize_t len = strlen(s);\n \t\tfor (int i = 0; i < len; ++i)\n \t\t{\n \t\t\tif (mapST[s[i]] == 0 && mapTS[t[i]] == 0)\n \t\t\t{\n \t\t\t\tmapST[s[i]] = t[i];\n \t\t\t\tmapTS[t[i]] = s[i];\n \t\t\t}\n \t\t\telse\n \t\t\t{\n \t\t\t\tif (mapST[s[i]] != t[i] || mapTS[t[i]] != s[i])\n \t\t\t\t\treturn false;\n \t\t\t}\n \t\t}\n \t\treturn true; \n }
21
0
[]
1
isomorphic-strings
Use array as map+ bitset vs Hash map||0ms beats 100%
use-array-as-map-bitset-vs-hash-map0ms-b-ny1s
Intuition\n Describe your first thoughts on how to solve this problem. \nThis is a problem to judge whether there is a one-to-one correspondence between s & t.
anwendeng
NORMAL
2024-04-02T01:33:17.046761+00:00
2024-04-02T11:59:03.306095+00:00
10,420
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThis is a problem to judge whether there is a one-to-one correspondence between s & t.\nMy idea is to construct the mapping st:s->t & inverse map ts:t->s, if possible.\n\n3 C++ codes, 1x array+biset, 1 x unordered_map & 1x just array.\nThe 3rd one is optimized.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n[Please turn on English subtitles if necessary]\n[https://youtu.be/3NDqQkf8z_Y?si=uIAKb9zBAaBAPwxo](https://youtu.be/3NDqQkf8z_Y?si=uIAKb9zBAaBAPwxo)\nProblem is solved long ago by hash tables (unordered_map).\nA new version is made by using arrays as mappings & bitset to record the alphabets used.\n1. Creat 2 arrays st, ts which map s[i] to t[i] & t[i] to s[i]\n2. Use a loop to see whether there is a wrong mapping, and record the alphabets used in s & t.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n $$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n $$O(256)$$\n# Code ||C++ 0ms beats 100%\n```\n#pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n bool isIsomorphic(string& s, string& t) { \n int n = s.size();\n // Using size 256 for ASCII characters\n bitset<256> s_char=0, t_char=0;\n char st[256]={0};\n char ts[256]={0};\n \n for(int i = 0; i < n; i++) {\n char cs = s[i], ct = t[i];\n if(s_char[cs]==0 && t_char[ct]==0) {\n st[cs]=ct;\n ts[ct]=cs;\n s_char[cs]=1;\n t_char[ct]=1;\n }\n else {\n if(st[cs]!=ct || ts[ct]!=cs){\n // cout<<"["<<i<<"] wrong mapping with cs="<<cs<<", ct="<<ct<<endl;\n return 0;\n }\n }\n }\n return 1;\n }\n};\n\n\nauto init = []()\n{ \n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n```\n# C++/Python using hash map (C++ unordered_map/Python dict)\n```python []\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n n=len(s)\n st={}\n ts={}\n for i in range(n):\n cs=s[i]\n ct=t[i]\n if cs not in st and ct not in ts:\n st[cs]=ct\n ts[ct]=cs\n elif cs in st and st[cs] != ct: \n return False\n elif ct in ts and ts[ct] != cs: \n return False\n return True\n\n\n \n```\n```C++ []\n#pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n bool isIsomorphic(string& s, string& t) { \n int n=s.size();\n unordered_map<char, char> st, ts;\n for(int i=0; i<n; i++){\n char cs=s[i], ct=t[i];\n if (st.count(cs)==0 && ts.count(ct)==0){\n st[cs]=ct;\n ts[ct]=cs;\n } \n else{\n if(st[cs]!=ct || ts[ct]!=cs) return 0;\n } \n }\n return 1;\n }\n};\n\n```\n# C++/Python array version||0ms beats 100%\n\nThe bitset is dropped off, the size for arrays st & ts is reduced to the half, which are initialized with 127 (ascii code for 127 is del which will not occur, -1 for Python) as unused. \n```C++ []\n#pragma GCC optimize("O3", "unroll-loops")\nclass Solution {\npublic:\n bool isIsomorphic(string& s, string& t) { \n int n = s.size();\n // Using size 128 for ASCII characters\n char st[128], ts[128];\n memset(st, 127, sizeof(st));\n memset(ts, 127, sizeof(ts));\n\n for(int i = 0; i < n; i++) {\n char cs = s[i], ct = t[i];\n if(st[cs]==127 && ts[ct]==127) {\n st[cs]=ct;\n ts[ct]=cs;\n }\n else {\n if(st[cs]!=ct || ts[ct]!=cs){\n // cout<<"["<<i<<"] wrong mapping with cs="<<cs<<", ct="<<ct<<endl;\n return 0;\n }\n }\n }\n return 1;\n }\n};\n```\n```python []\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n n=len(s)\n st=[-1]*128\n ts=[-1]*128\n for i in range(n):\n cs, ct= s[i], t[i]\n _cs=ord(cs)\n _ct=ord(ct)\n if st[_cs]==-1 and ts[_ct]==-1:\n st[_cs]=ct\n ts[_ct]=cs\n elif st[_cs]!=ct or ts[_ct]!=cs: \n return False\n return True\n\n\n \n```\n
19
0
['Array', 'Hash Table', 'Bit Manipulation', 'C++', 'Python3']
6
isomorphic-strings
✅ [Accepted] Solution for Swift
accepted-solution-for-swift-by-asahiocea-z94x
\nDisclaimer: By using any content from this post or thread, you release the author(s) from all liability and warranties of any kind. You can are to use the con
AsahiOcean
NORMAL
2021-03-22T23:58:13.623360+00:00
2022-06-20T01:24:07.832559+00:00
1,760
false
<blockquote>\n<b>Disclaimer:</b> By using any content from this post or thread, you release the author(s) from all liability and warranties of any kind. You can are to use the content as you see fit. Any suggestions for improvement are welcome and greatly appreciated! Happy coding!\n</blockquote>\n\n```swift\nclass Solution {\n func isIsomorphic(_ s: String, _ t: String) -> Bool {\n var sdc = [Character:String.Index](), tdc = sdc\n for i in s.indices {\n guard sdc[s[i]] == tdc[t[i]] else { return false }\n sdc[s[i]] = i\n tdc[t[i]] = i\n }\n return true\n }\n}\n```
19
0
['Swift']
2
isomorphic-strings
[C++] Array-based Solution Explained, 100% Time, 100% Space
c-array-based-solution-explained-100-tim-zeoi
Pretty simple problem, but again I preferred to challenge me a bit and not go for an easy/lazy/inefficient approach with hashmaps: since we know that we are lik
ajna
NORMAL
2020-09-08T18:41:00.250300+00:00
2021-07-12T08:39:00.968068+00:00
3,518
false
Pretty simple problem, but again I preferred to challenge me a bit and not go for an easy/lazy/inefficient approach with hashmaps: since we know that we are likely to get a limited amount of different characters (annoyingly not specified in the specs), I needed to make a few bets and decide to store the already seen one into an array, `seen`, initialised with all the values set to `0` and which would then store the already seen one.\n\nAnd that is what we do in our main loop: we iterate through all the characters in `s` and we do 2 possible things:\n* if we have never seen c, we check if by any chance it matches any known character (other annoying, unstated requirement like the one in [this problem](https://leetcode.com/problems/word-pattern/discuss/834656/)) and if not, we update `seen` accordingly for the index `c`;\n* if we already encountered, we check if it matches the record we stored and return `false` otherwise.\n\nWhen the main loop is done, it means the 2 strings are isomorphic and thus we return `true` :)\n\nThe code:\n\n```cpp\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n // support variables\n int len = s.size();\n char seen[128] = {};\n for (int i = 0; i < len; i++) {\n // checking s, char by char\n char c = s[i];\n if (!seen[c]) {\n // if we never saw this, we check it does not match any other seen\n for (char s: seen) if (s == t[i]) return false;\n // and if so, we store it\n seen[c] = t[i];\n }\n // if already seen, we check if it matches the previous record\n else if (seen[c] != t[i]) return false;\n }\n return true;\n }\n};\n```
19
0
['String', 'C', 'C++']
4
isomorphic-strings
JavaScript 91.97%
javascript-9197-by-cindy0092-s8t9
used two objects to cross-reference\n\nvar isIsomorphic = function(s, t) {\n if (s.length !== t.length) {\n return false;\n }\n if (s === t) {\n
cindy0092
NORMAL
2019-03-28T14:08:43.395122+00:00
2019-03-28T14:08:43.395165+00:00
2,007
false
used two objects to cross-reference\n```\nvar isIsomorphic = function(s, t) {\n if (s.length !== t.length) {\n return false;\n }\n if (s === t) {\n return true;\n }\n const obj1 = {};\n const obj2 = {};\n for(let i = 0; i < s.length; i++) {\n const letter = s[i];\n const tLetter = t[i];\n if (!obj2[tLetter]) {\n obj2[tLetter] = letter;\n }\n if (!obj1[letter]) {\n obj1[letter] = tLetter;\n }\n if (obj1[letter] !== tLetter || obj2[tLetter] !== letter) {\n return false;\n }\n }\n return true;\n};\n```
19
1
[]
0
isomorphic-strings
✅Super Easy HashMap (C++/Java/Python) Solution With Detailed Explanation✅
super-easy-hashmap-cjavapython-solution-i9mro
Intuition\nThe intuition checks if two strings, s and t, are isomorphic by ensuring a one-to-one correspondence between each character in s and t using two hash
suyogshete04
NORMAL
2024-04-02T01:53:46.680282+00:00
2024-04-02T05:01:11.928029+00:00
12,826
false
# Intuition\nThe intuition checks if two strings, `s` and `t`, are isomorphic by ensuring a one-to-one correspondence between each character in `s` and `t` using two hash maps. It iterates through both strings simultaneously, verifying existing mappings for consistency and creating new mappings when necessary. If it encounters an inconsistency or a character in `t` already mapped to another character in `s`, it returns false. \n\n# Approach\n\n1. **Initialization**: Two hash maps (`unordered_map` in C++) `mapS2T` and `mapT2S` are initialized. These maps store the character mappings from `s` to `t` and from `t` to `s`, respectively.\n\n2. **Iteration**: The algorithm iterates through each character in the strings `s` and `t` simultaneously, using an index `i`.\n\n3. **Mapping Validation**:\n - For each character `charS` in `s` at index `i`, the algorithm checks if there is an existing mapping in `mapS2T`.\n - If there is an existing mapping, it checks if `charS` is correctly mapped to `charT` (the character in `t` at the same index). If not, the strings are not isomorphic, and the function returns `false`.\n - If there is no existing mapping for `charS`, it checks if `charT` is already mapped to a different character in `mapT2S`. If so, this means that `charT` is expected to map to two different characters, which violates the one-to-one mapping rule, and the function returns `false`.\n\n4. **Creating New Mappings**: If the checks pass, it means the current characters `charS` and `charT` can be mapped to each other. The algorithm then adds these new mappings to `mapS2T` and `mapT2S`.\n\n5. **Completion**: If the algorithm successfully iterates through all characters without returning `false`, it means that all character mappings are valid, and the strings are isomorphic. The function then returns `true`.\n\n## Complexity Analysis\n\n- **Time Complexity**: O(N), where N is the length of the strings. The algorithm iterates through each character of the strings exactly once. The operations within each iteration (accessing and updating the hash maps) are on average constant time, O(1), thanks to the nature of `unordered_map` in C++. Thus, the overall time complexity is linear in the size of the input strings.\n\n- **Space Complexity**: O(N), in the worst case. This is because, in the worst-case scenario, each character in the strings `s` and `t` could be different, requiring each character to be stored in both `mapS2T` and `mapT2S`. However, since the domain of characters (for example, ASCII characters) is limited, this space complexity could also be considered O(1) in practice if the character set is fixed and limited in size.\n\n# Code\n```C++ []\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n \n unordered_map<char, char> mapS2T;\n unordered_map<char, char> mapT2S;\n \n for (int i = 0; i < s.size(); ++i) {\n char charS = s[i];\n char charT = t[i];\n \n // Check if there\'s a mapping for charS in mapS2T and if it maps to the same character in t\n if (mapS2T.find(charS) != mapS2T.end()) {\n if (mapS2T[charS] != charT) {\n return false;\n }\n } else { // If no mapping exists, check if charT is already mapped to some other character in mapT2S\n if (mapT2S.find(charT) != mapT2S.end()) {\n return false;\n }\n \n // Create new mapping since it\'s valid\n mapS2T[charS] = charT;\n mapT2S[charT] = charS;\n }\n }\n \n return true;\n }\n};\n```\n```Java []\nimport java.util.HashMap;\n\npublic class Solution {\n public boolean isIsomorphic(String s, String t) {\n \n HashMap<Character, Character> mapS2T = new HashMap<>();\n HashMap<Character, Character> mapT2S = new HashMap<>();\n \n for (int i = 0; i < s.length(); i++) {\n char charS = s.charAt(i);\n char charT = t.charAt(i);\n \n // Check if there\'s a mapping for charS in mapS2T and if it maps to the same character in t\n if (mapS2T.containsKey(charS)) {\n if (mapS2T.get(charS) != charT) {\n return false;\n }\n } else { // If no mapping exists, check if charT is already mapped to some other character in mapT2S\n if (mapT2S.containsKey(charT)) {\n return false;\n }\n \n // Create new mapping since it\'s valid\n mapS2T.put(charS, charT);\n mapT2S.put(charT, charS);\n }\n }\n \n return true;\n }\n \n \n}\n```\n```Python []\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n if len(s) != len(t):\n return False\n\n mapS2T = {}\n mapT2S = {}\n\n for charS, charT in zip(s, t):\n # If the character in s already has a mapping, check if it maps to the correct character in t\n if charS in mapS2T:\n if mapS2T[charS] != charT:\n return False\n else:\n # If the character in t is already mapped to a different character in s, return false\n if charT in mapT2S:\n return False\n\n # Map the characters in s to t and vice versa\n mapS2T[charS] = charT\n mapT2S[charT] = charS\n\n return True\n\n```\n## Please upvote if it helped you..!!
18
0
['Hash Table', 'String', 'C++', 'Java', 'Python3']
10
isomorphic-strings
JAVASCRIPT 100% WITH EXPLANATION || 92% BEATS || HASH MAPS
javascript-100-with-explanation-92-beats-0scl
Intuition\nThe isomorphic strings problem asks us to determine if two strings have the same pattern of character occurrences. For example, the strings "egg" and
ikboljonme
NORMAL
2023-03-27T13:39:34.203020+00:00
2023-03-27T13:44:46.588114+00:00
1,928
false
# Intuition\nThe isomorphic strings problem asks us to determine if two strings have the same pattern of character occurrences. For example, the strings "egg" and "add" are isomorphic because they both have the pattern "abb", where "a" is mapped to "e" and "b" is mapped to "d". On the other hand, the strings "foo" and "bar" are not isomorphic because they do not have the same pattern of character occurrences.\n\nTo solve this problem, we can iterate through the characters of both strings simultaneously and maintain a mapping between the characters of one string and the characters of the other string. We can use a hash map to store this mapping and check whether each character in the strings is mapped to the same character in the other string. If we find any inconsistencies in the mapping, we can conclude that the strings are not isomorphic. Otherwise, we can conclude that the strings are isomorphic.\n\n# Approach\n1. Create two empty hash maps mapS and mapT.\n2. Iterate over the characters of the input strings s and t simultaneously.\n3. For each character pair s[i] and t[i]:\nIf s[i] is not present in mapS and t[i] is not present in mapT, add a new mapping s[i] -> t[i] to mapS and t[i] -> s[i] to mapT.\nIf s[i] is already mapped to a character c in mapS and t[i] is not mapped to c, or if t[i] is already mapped to a character c in mapT and s[i] is not mapped to c, return false.\n4. If all character pairs are processed without returning false, return true.\n\n# Complexity\n- Time complexity:\nThe time complexity of this function is O(n), where n is the length of the input strings s and t. This is because the function iterates through each character of the input strings only once.\n\n- Space complexity:\nThe space complexity of this function is O(k), where k is the number of distinct characters in the input strings s and t. This is because the function uses two hash maps mapS and mapT to store the mappings between characters, and the space required by these hash maps is proportional to the number of distinct characters in the input strings.\n\n# Code\n```\n/**\n * @param {string} s\n * @param {string} t\n * @return {boolean}\n */\nvar isIsomorphic = function (s, t) {\nconst mapS = new Map();\n const mapT = new Map();\n\n for (let i = 0; i < s.length; i++) {\n const charS = s[i];\n const charT = t[i];\n\n if ((!mapS.has(charS) && !mapT.has(charT))) {\n mapS.set(charS, charT);\n mapT.set(charT, charS);\n } else if (mapS.get(charS) !== charT || mapT.get(charT) !== charS) {\n return false;\n }\n }\n\n return true;\n};\n\n```
18
0
['JavaScript']
0
isomorphic-strings
C++ solution with hashmap
c-solution-with-hashmap-by-lhqqqqq-td65
class Solution {\n public:\n bool isIsomorphic(string s, string t) {\n if (s.empty())\n return true;\n return hel
lhqqqqq
NORMAL
2015-04-29T03:02:03+00:00
2018-09-21T01:05:17.034320+00:00
4,784
false
class Solution {\n public:\n bool isIsomorphic(string s, string t) {\n if (s.empty())\n return true;\n return helper(s, t) && helper(t, s);\n }\n bool helper(string s, string t) {\n \tunordered_map<char, char> m;\n for (auto i = 0; i != s.size(); ++i) {\n if (!m.count(s[i])) {\n m.insert({s[i], t[i]});\n }\n \telse if (m[s[i]] != t[i])\n return false;\n }\n return true;\n }\n };
17
0
['C++']
3
isomorphic-strings
🔥 [LeetCode The Hard Way]🔥 Hash Map | Explained Line By Line
leetcode-the-hard-way-hash-map-explained-1ojr
Please check out LeetCode The Hard Way for more solution explanations and tutorials. If you like it, please give a star, watch my Github Repository and upvote t
__wkw__
NORMAL
2022-09-07T05:48:52.045304+00:00
2022-09-07T05:48:52.045348+00:00
1,312
false
Please check out [LeetCode The Hard Way](https://wingkwong.github.io/leetcode-the-hard-way/) for more solution explanations and tutorials. If you like it, please give a star, watch my [Github Repository](https://github.com/wingkwong/leetcode-the-hard-way) and upvote this post.\n\n---\n\n```cpp\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n // m1 is used to map s[i] to t[i]\n // m2 is used to map t[i] to s[i]\n // example 1:\n // m1[\'e\'] --> \'a\'\n // m1[\'g\'] --> \'d\'\n // m2[\'a\'] --> \'e\'\n // m2[\'d\'] --> \'g\'\n unordered_map<char, char> m1, m2;\n for (int i = 0; i < s.size(); i++) {\n // if s[i] isn\'t in m1 and t[i] isn\'t in m2\n if (!m1.count(s[i]) && !m2.count(t[i])) {\n // then we can map s[i] to t[i]\n m1[s[i]] = t[i];\n // and t[i] to s[i]\n m2[t[i]] = s[i];\n } else {\n // if they are they are isomorphic,\n // m1[s[i]] should map to t[i], and m2[t[i]] should map to s[i]\n // we return false here if this condition is not satisfied\n if (m1[s[i]] != t[i] || m2[t[i]] != s[i]) {\n return false;\n }\n }\n }\n // they are isomorphic\n return true;\n }\n};\n```
16
0
['C', 'C++']
4
isomorphic-strings
Python solution
python-solution-by-zitaowang-6gm8
\nclass Solution(object):\n def isIsomorphic(self, s, t):\n """\n :type s: str\n :type t: str\n :rtype: bool\n """\n
zitaowang
NORMAL
2018-08-17T05:33:19.007453+00:00
2018-10-11T20:20:16.950285+00:00
2,038
false
```\nclass Solution(object):\n def isIsomorphic(self, s, t):\n """\n :type s: str\n :type t: str\n :rtype: bool\n """\n n = len(s)\n m = len(t)\n if n != m:\n return False\n dic = {}\n for i in range(n):\n if s[i] in dic:\n if dic[s[i]] != t[i]:\n return False\n elif t[i] in dic.values():\n return False\n else:\n dic[s[i]] = t[i]\n return True\n```
16
0
[]
1
isomorphic-strings
C++/Java/Python/JavaScript || ✅🚀O(n) Using Map Simple Solution || ✔️🔥Easy To Understand
cjavapythonjavascript-on-using-map-simpl-cg6d
Intuition\nTwo strings are considered isomorphic if the characters in one string can be replaced by the characters in the other string in such a way that the tw
devanshupatel
NORMAL
2023-05-20T14:36:09.531510+00:00
2023-05-20T19:33:52.617363+00:00
7,147
false
# Intuition\nTwo strings are considered isomorphic if the characters in one string can be replaced by the characters in the other string in such a way that the two strings become identical.\n\n# Approach\nThe Solution uses a `map<char, char>` to store the mapping between characters of string `s` and string `t`, and a `set<char>` to keep track of characters in string `t` that have already been mapped to characters in string `s`.\n\nThe Solution iterates through the characters of the strings from right to left, starting from the last character (index `n`). It performs the following checks for each character:\n\n1. If the character `s[n]` is already present in the map and it is mapped to a different character `t[n]`, then the strings are not isomorphic. In this case, the function returns `false`.\n\n2. If the character `s[n]` is not present in the map but the character `t[n]` is already present in the set, then the strings are not isomorphic. In this case, the function returns `false`.\n\n3. Otherwise, the function proceeds to insert the character `t[n]` into the set and map the character `s[n]` to `t[n]` in the map.\n\nAfter iterating through all the characters, if no inconsistencies are found, the function returns `true`, indicating that the strings are isomorphic.\n\n# Complexity\n- The time complexity of this approach is O(n), where n is the length of the strings `s` and `t`. This is because the code iterates through each character once.\n\n- The space complexity is also O(n) because in the worst case, all characters of string `t` need to be stored in the set and map.\n\n# C++\n```\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n map<char,char> map;\n set<char> set;\n int n = s.size()-1;\n while(n>=0){\n if(map.count(s[n]) && map[s[n]] != t[n]){\n return false;\n }\n if( !map.count(s[n]) && set.count(t[n])){\n return false;\n }\n set.insert(t[n]);\n map[s[n]]=t[n];\n n--;\n }\n return true;\n }\n};\n```\n# Java\n```\nclass Solution {\n public boolean isIsomorphic(String s, String t) {\n Map<Character, Character> map = new HashMap<>();\n Set<Character> set = new HashSet<>();\n int n = s.length() - 1;\n \n while (n >= 0) {\n if (map.containsKey(s.charAt(n)) && map.get(s.charAt(n)) != t.charAt(n)) {\n return false;\n }\n if (!map.containsKey(s.charAt(n)) && set.contains(t.charAt(n))) {\n return false;\n }\n set.add(t.charAt(n));\n map.put(s.charAt(n), t.charAt(n));\n n--;\n }\n \n return true;\n }\n}\n```\n# Python\n```\nclass Solution(object):\n def isIsomorphic(self, s, t):\n mapping = {}\n char_set = set()\n n = len(s) - 1\n\n while n >= 0:\n if s[n] in mapping and mapping[s[n]] != t[n]:\n return False\n if s[n] not in mapping and t[n] in char_set:\n return False\n char_set.add(t[n])\n mapping[s[n]] = t[n]\n n -= 1\n\n return True\n\n```\n# JavaScript\n```\nvar isIsomorphic = function(s, t) {\n const map = new Map();\n const set = new Set();\n let n = s.length - 1;\n\n while (n >= 0) {\n if (map.has(s[n]) && map.get(s[n]) !== t[n]) {\n return false;\n }\n if (!map.has(s[n]) && set.has(t[n])) {\n return false;\n }\n set.add(t[n]);\n map.set(s[n], t[n]);\n n--;\n }\n\n return true;\n};\n```\n
15
0
['Hash Table', 'Python', 'C++', 'Java', 'JavaScript']
1
isomorphic-strings
C++ Simple and Clean Solution Using Normalized Pattern, 7 Lines
c-simple-and-clean-solution-using-normal-4xvn
Normalize both strings to the same pattern.\n\nclass Solution {\npublic:\n string normalize_pattern(string word) {\n unordered_map<char, char> m;\n
yehudisk
NORMAL
2021-07-12T07:33:33.772769+00:00
2021-07-12T07:34:54.706261+00:00
2,929
false
Normalize both strings to the same pattern.\n```\nclass Solution {\npublic:\n string normalize_pattern(string word) {\n unordered_map<char, char> m;\n char curr = \'a\';\n \n for (auto letter : word)\n if (!m[letter]) m[letter] = curr++;\n \n for (int i = 0; i < word.size(); i++) word[i] = m[word[i]];\n \n return word;\n \n }\n \n bool isIsomorphic(string s, string t) {\n return normalize_pattern(s) == normalize_pattern(t);\n }\n};\n```\n**Like it? please upvote!**
15
1
['C']
2
isomorphic-strings
1-liner in Python
1-liner-in-python-by-stefanpochmann-tu4d
Edit: For an even shorter solution, check out mathsam's answer below and my comment on it.\n\n class Solution:\n def isIsomorphic(self, s, t):\n
stefanpochmann
NORMAL
2015-05-19T22:43:26+00:00
2015-05-19T22:43:26+00:00
6,985
false
Edit: For an even shorter solution, check out mathsam's answer below and my comment on it.\n\n class Solution:\n def isIsomorphic(self, s, t):\n return all(map({}.setdefault, a, b) == list(b) for a, b in ((s, t), (t, s)))
15
5
['Python']
8
isomorphic-strings
Very Easy Solution C++ using both 1 Hashmap and 2 Hashmaps
very-easy-solution-c-using-both-1-hashma-3sp3
```\nunordered_map mp1, mp2; //we take 2 unordered maps\n int n = s.length();\n int m = t.length();\n \n if(n != m){ //if there si
tanu_0208
NORMAL
2023-03-25T19:13:56.567099+00:00
2023-03-26T17:36:50.840773+00:00
2,484
false
```\nunordered_map<char, int> mp1, mp2; //we take 2 unordered maps\n int n = s.length();\n int m = t.length();\n \n if(n != m){ //if there size is not the same no need to go furthur simply return false\n return false; \n }\n \n for(int i=0; i<n; i++){\n \n if(mp1[s[i]] != mp2[t[i]]) //we map the char with the index+1\n return false;\n \n mp1[s[i]] = i+1; //now why do we need to do index+1?\n\t\t\tmp2[t[i]] = i+1; //try s="ppaer" and t="title" Got the ans?\n \n }\n return true; \n ----------------------------------------------------------------------------------------------------------------------------\n //by using single hash map\n \n bool solve(string s,string t){\n \n map<char,char>mp;\n \n for(int i=0;i<s.size();i++){\n \n if(mp.find(s[i])!=mp.end()){\n if(mp[s[i]]!=t[i]) \n return false;\n }\n \n else \n mp[s[i]]=t[i]; //mapping of character to character\n }\n return true;\n}\n\n bool isIsomorphic(string s, string t) {\n \n if(s.length() != t.length())\n return false;\n \n return (solve(s,t) and solve(t,s)); //we need to check both ways testcase "badc" "baba"\n \n }\n};\n \n\n\tIf you liked the solution do upvote, it helps.\n\tHappy Leetcoding :)\n
14
0
['String', 'C']
4
isomorphic-strings
205: Solution with step by step explanation
205-solution-with-step-by-step-explanati-5r64
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\nThis solution uses two hash maps to keep track of the mapping of characte
Marlen09
NORMAL
2023-02-23T20:12:56.879135+00:00
2023-02-23T20:12:56.879168+00:00
5,891
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nThis solution uses two hash maps to keep track of the mapping of characters from string s to string t and vice versa. It iterates over the characters in the strings, and if a character is not already in either hash map, it adds the mapping of that character from s to t and from t to s in their respective hash maps. If the character is already in either hash map, it checks if the mapping is the same as the character in the other string. If not, it returns False. If the loop completes without returning False, it returns True.\n\nThis solution has a time complexity of O(n), where n is the length of the strings, as it only iterates over the characters once. The space complexity is also O(n), as it uses two hash maps to store the mappings.\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n if len(s) != len(t):\n return False\n \n s_to_t = {}\n t_to_s = {}\n for i in range(len(s)):\n if s[i] not in s_to_t and t[i] not in t_to_s:\n s_to_t[s[i]] = t[i]\n t_to_s[t[i]] = s[i]\n elif s[i] in s_to_t and s_to_t[s[i]] == t[i]:\n continue\n else:\n return False\n \n return True\n\n\n\n```
14
0
['Hash Table', 'String', 'Python', 'Python3']
2
isomorphic-strings
✅C++ solution with hash tables
c-solution-with-hash-tables-by-coding_me-26ov
My GitHub: https://github.com/crimsonKn1ght\n\n\nC++ []\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n unordered_map<char, cha
coding_menance
NORMAL
2022-10-14T18:19:19.381536+00:00
2022-10-31T11:12:43.028846+00:00
3,261
false
## My GitHub: https://github.com/crimsonKn1ght\n\n\n``` C++ []\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n unordered_map<char, char> mp, mp2;\n for (int i=0; i<s.length(); ++i) {\n if (mp[s[i]] && mp[s[i]]!=t[i]) return false;\n if (mp2[t[i]] && mp2[t[i]]!=s[i]) return false;\n mp[s[i]]=t[i];\n mp2[t[i]]=s[i];\n }\n return true;\n }\n};\n```\n*Please upvote to motivate me to write more solutions*\n\n
14
0
['Hash Table', 'String', 'C++']
2
isomorphic-strings
Simple JavaScript solution, faster 96.72%~
simple-javascript-solution-faster-9672-b-neic
\nvar isIsomorphic = function(s, t) {\n let mapS = {}, mapT = {};\n for (let i = 0; i < s.length; i++) {\n if (!mapS[s[i]] && !mapT[t[i]]) {\n
UDN
NORMAL
2022-08-07T04:27:44.978622+00:00
2022-08-07T04:27:44.978646+00:00
2,353
false
```\nvar isIsomorphic = function(s, t) {\n let mapS = {}, mapT = {};\n for (let i = 0; i < s.length; i++) {\n if (!mapS[s[i]] && !mapT[t[i]]) {\n mapS[s[i]] = t[i];\n mapT[t[i]] = s[i];\n } else if (mapS[s[i]] !== t[i] || mapT[t[i]] !== s[i]) return false;\n } \n return true;\n};\n```\n\n![image](https://assets.leetcode.com/users/images/cb40c5e4-b5b7-47fd-918f-856cfeec593b_1659846333.7821708.png)\n
14
0
['JavaScript']
2
isomorphic-strings
Ruby short functional solution
ruby-short-functional-solution-by-rowan4-7lgl
ruby\n# @param {String} s\n# @param {String} t\n# @return {Boolean}\ndef is_isomorphic(s, t)\n s.chars.map{ |c| s.index(c) } == t.chars.map{ |c| t.index(c) }
Rowan441
NORMAL
2022-06-28T04:42:28.108007+00:00
2022-06-28T04:42:28.108041+00:00
456
false
```ruby\n# @param {String} s\n# @param {String} t\n# @return {Boolean}\ndef is_isomorphic(s, t)\n s.chars.map{ |c| s.index(c) } == t.chars.map{ |c| t.index(c) }\nend\n```\n\n* For both inputs (`s` & `t`) map each letter to the index of the first occurence of that letter in the string (e.g egg => [0, 1, 1])\n* If the mapped values are the same, the string is isomorphic
14
0
['Ruby']
0
isomorphic-strings
C++ 8ms - simple solution
c-8ms-simple-solution-by-rantos22-p9wi
class Solution {\n public:\n bool isIsomorphic(string s, string t) \n {\n const size_t n = s.size();\n if ( n != t.size()
rantos22
NORMAL
2015-04-29T10:42:03+00:00
2015-04-29T10:42:03+00:00
4,466
false
class Solution {\n public:\n bool isIsomorphic(string s, string t) \n {\n const size_t n = s.size();\n if ( n != t.size())\n return false;\n \n unsigned char forward_map[256] = {}, reverse_map[256] = {};\n \n for ( int i=0; i < n; ++i)\n {\n unsigned char c1 = s[i];\n unsigned char c2 = t[i];\n \n if ( forward_map[c1] && forward_map[c1] != c2)\n return false;\n \n if ( reverse_map[c2] && reverse_map[c2] != c1)\n return false;\n \n forward_map[c1] = c2;\n reverse_map[c2] = c1;\n }\n \n return true;\n }\n };
14
0
[]
1
isomorphic-strings
Java solution || easy approach using hash map || beginner friendly ||
java-solution-easy-approach-using-hash-m-4v5n
//explained in code;str\n\n# Code\n\nclass Solution {\n public boolean isIsomorphic(String s, String t) {\n //first we check if theor length is equall
k_io
NORMAL
2023-01-26T12:01:32.817932+00:00
2023-01-26T12:01:32.817977+00:00
2,560
false
//explained in code;str\n\n# Code\n```\nclass Solution {\n public boolean isIsomorphic(String s, String t) {\n //first we check if theor length is equall or not;\n if(s.length() != t.length()){\n return false ;//if not then we return false ;\n }\n\n HashMap<Character , Character> hm = new HashMap<>();\n //then we make a hashmap to map the characters of string "s" to characters of string"t";\n\n //then we used a for loop to map them \n for(int i = 0 ; i <s.length() ; i++){\n if(hm.containsValue(t.charAt(i))){//this is important\n //we check if the value to which we are mapping is already mapped to other character then we don;t change it;\n continue ;\n }else{//else we map it ;\n hm.put(s.charAt(i),t.charAt(i));\n }\n \n }\n //then we made a string ubilder and used the mapped charcters to check if the string formed using mapped characters id equall\n //to other string or not ;\n StringBuilder sb = new StringBuilder();\n for(int i = 0 ; i <s.length() ;i++){\n sb.append(hm.get(s.charAt(i)));\n }\n //then we return it using a comparator ;\n return(sb.toString().equals(t));\n \n }\n}\n```
13
0
['String', 'Java']
2
isomorphic-strings
Easy java solution with explanation
easy-java-solution-with-explanation-by-u-cnbl
For s to be Isomorphic t ,t should also be Isomorphic to s\n Here I have used 2 maps as both the strings are of same length we can iterate only once\n get the
uj2208
NORMAL
2022-07-20T15:22:29.209548+00:00
2022-07-20T15:22:51.493141+00:00
1,176
false
* For s to be Isomorphic t ,t should also be Isomorphic to s\n* Here I have used 2 maps as both the strings are of same length we can iterate only once\n* get the individual characters of each string and map them with other character of the 2nd string\n* but before that check if map1 has key (s[i]) and map.get(s[i]!=t[i]) or map2 has key (t[i]) and map.get(t[i]!=s[i])\n* if thats the case return false this ensures that different characters are not mapped to one character of either string\n* Retrun true at the end\n```\nclass Solution {\n public boolean isIsomorphic(String s, String t) {\n Map<Character,Character>mapst = new HashMap<>();\n Map<Character,Character>mapts = new HashMap<>();\n for(int i =0;i<s.length();i++){\n char chs = s.charAt(i);\n char cht = t.charAt(i);\n if(mapst.containsKey(chs) && mapst.get(chs)!=cht ||mapts.containsKey(cht) && mapts.get(cht)!=chs)\n return false;\n mapst.put(chs,cht);\n mapts.put(cht,chs);\n }\n return true;\n }\n}\n```\n\n***IF YOU LIKED THE APPROCH PLEASE UPVOTE !!***
13
0
['Java']
1
isomorphic-strings
[Java] TC: O(N) | SC: O(N) | Simple One-Pass solution using a Map & Set
java-tc-on-sc-on-simple-one-pass-solutio-bn5r
java\n/**\n * One-Pass solution using HashMap and HashSet\n *\n * Time Complexity:\n * - O(1) --> This will be in case S & T are of different lengths\n * - O(N)
NarutoBaryonMode
NORMAL
2021-11-02T22:28:36.065205+00:00
2021-11-02T22:41:52.283691+00:00
886
false
```java\n/**\n * One-Pass solution using HashMap and HashSet\n *\n * Time Complexity:\n * - O(1) --> This will be in case S & T are of different lengths\n * - O(N) --> If S & T are of same length, say N, the code will check the Isomorphic property in one-pass.\n *\n * - O(1) --> This will be in case S & T are of different lengths\n * - O(3*N) = O(N) --> If S & T are of same length, say N, the code will require 3 * N space for HashMap and HashSet.\n * </pre>\n */\nclass Solution {\n public boolean isIsomorphic(String s, String t) {\n if (s == null || t == null || s.length() != t.length()) {\n return false;\n }\n\n HashMap<Character, Character> map = new HashMap<>();\n HashSet<Character> visitedT = new HashSet<>();\n for (int i = 0; i < s.length(); i++) {\n char curS = s.charAt(i);\n char curT = t.charAt(i);\n\n // Finding the old character of T that maps to current character of S.\n Character oldT = map.put(curS, curT);\n\n if (oldT == null) {\n // Since the current char of S does not map to any older char of T, try adding\n // curT to the visitedT set to verify if curT is already seen before or not.\n if (!visitedT.add(curT)) {\n return false;\n }\n } else if (!oldT.equals(curT)) {\n return false;\n }\n }\n\n return true;\n }\n}\n```
12
0
['String', 'Java']
1
isomorphic-strings
Java clean code using hashmap (simple solution)
java-clean-code-using-hashmap-simple-sol-jhdn
<-----If you like the solution . Kindly UPvote for better reach\n\nclass Solution {\n public boolean isIsomorphic(String s, String t) {\n HashMap<Char
adarsh1405
NORMAL
2021-07-13T04:11:41.306014+00:00
2021-07-16T11:46:34.546622+00:00
973
false
<-----**If you like the solution . Kindly UPvote for better reach**\n```\nclass Solution {\n public boolean isIsomorphic(String s, String t) {\n HashMap<Character,Character> hm = new HashMap<>();\n if(s.length()!=t.length())\n return false;\n \n for(int i=0;i<s.length();i++)\n {\n if(hm.containsKey(s.charAt(i)))\n {\n if(hm.get(s.charAt(i))!=t.charAt(i))\n return false;\n }\n else if(hm.containsValue(t.charAt(i)))\n return false;\n else\n hm.put(s.charAt(i),t.charAt(i));\n } \n return true;\n }\n}\n```
12
2
['Java']
2
isomorphic-strings
10 lines C solution, without hash table
10-lines-c-solution-without-hash-table-b-0c7p
bool isIsomorphic(char* s, char* t){\n \tif(!(s&&t))\n \t\treturn false;\n \tchar *spt = s, *tpt=t;\n \twhile(*spt != '\\0'){\n \t\tif( strchr(s,
yxmy
NORMAL
2015-06-13T08:17:05+00:00
2015-06-13T08:17:05+00:00
1,307
false
bool isIsomorphic(char* s, char* t){\n \tif(!(s&&t))\n \t\treturn false;\n \tchar *spt = s, *tpt=t;\n \twhile(*spt != '\\0'){\n \t\tif( strchr(s, *spt++)-s != strchr(t, *tpt++)-t)\n \t\t\treturn false;\n \t}\n \treturn true;\n }\n\nTwo strings s and t are not isomorphic if for every index i, s[i] and t[i] first appear in string s and t, respectively, in different position.
12
0
['C']
1
isomorphic-strings
8ms c++ simple solution
8ms-c-simple-solution-by-wtsanshou-o3pl
\n bool isIsomorphic(string s, string t) {\n int cs[128] = {0}, ct[128] = {0};\n for(int i=0; i<s.size(); i++)\n {\n if(cs[s[
wtsanshou
NORMAL
2016-06-28T18:36:29+00:00
2016-06-28T18:36:29+00:00
5,882
false
\n bool isIsomorphic(string s, string t) {\n int cs[128] = {0}, ct[128] = {0};\n for(int i=0; i<s.size(); i++)\n {\n if(cs[s[i]] != ct[t[i]]) return false;\n else if(!cs[s[i]]) //only record once\n {\n cs[s[i]] = i+1;\n ct[t[i]] = i+1;\n }\n }\n return true;\n }
12
0
['C++']
7
isomorphic-strings
✅ One Line Solution
one-line-solution-by-mikposp-y6va
(Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)\n\n# Code #1\nTime complexity: O(n). Space complexi
MikPosp
NORMAL
2024-04-02T11:34:30.089546+00:00
2024-04-02T16:30:18.111370+00:00
2,454
false
(Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)\n\n# Code #1\nTime complexity: $$O(n)$$. Space complexity: $$O(1)$$.\n```\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n return len({*zip(s,t)})==len({*s})==len({*t})\n```\n\n# Code #2.1\nTime complexity: $$O(n^2)$$. Space complexity: $$O(n)$$.\n```\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n return [*map(s.find,s)]==[*map(t.find,t)]\n```\n\n# Code #2.2\nTime complexity: $$O(n^2)$$. Space complexity: $$O(1)$$.\n```\nclass Solution:\n def isIsomorphic(self, *a: str) -> bool:\n return all(starmap(eq,zip(*(map(s.find,s) for s in a))))\n```\n\n# Code #3.1 (seen [here](https://leetcode.com/problems/isomorphic-strings/solutions/1333439/python-3-one-line/))\nTime complexity: $$O(n)$$. Space complexity: $$O(n)$$.\n```\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n return [*map({}.setdefault,s,count())]==[*map({}.setdefault,t,count())]\n```\n\n# Code #3.2\nTime complexity: $$O(n)$$. Space complexity: $$O(1)$$.\n```\nclass Solution:\n def isIsomorphic(self, *a: str) -> bool:\n return all(starmap(eq,zip(*(map({}.setdefault,s,count()) for s in a))))\n```\n\n# Code #4 (seen [here](https://leetcode.com/problems/isomorphic-strings/solutions/4960129/two-one-line-solutions/))\nTime complexity: $$O(n)$$. Space complexity: $$O(1)$$.\n```\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n return (p:={},q:={}) and all(p.setdefault(a,b)==b and q.setdefault(b,a)==a for a,b in zip(s,t))\n```\n\n# Code #5.1 (seen [here](https://leetcode.com/problems/isomorphic-strings/solutions/126446/36ms-python-one-line-solution/))\nTime complexity: $$O(n)$$. Space complexity: $$O(n)$$.\n```\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n return s==t.translate(t.maketrans(t,s)) and t==s.translate(s.maketrans(s,t))\n```\n\n# Code #5.2\nTime complexity: $$O(n)$$. Space complexity: $$O(n)$$.\n```\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n return (f:=lambda p,q:p==q.translate(q.maketrans(q,p)))(s,t) and f(t,s)\n```\n\n(Disclaimer 2: all code above is just a product of fantasy, it is not claimed to be pure impeccable oneliners - please, remind about drawbacks only if you know how to make it better. PEP 8 is violated intentionally)
11
0
['Hash Table', 'String', 'Python', 'Python3']
0
isomorphic-strings
[C++] Map Character to Index
c-map-character-to-index-by-awesome-bug-uqrk
Intuition\n Describe your first thoughts on how to solve this problem. \n- Convert each character to an integer, which is the appearance order in the string\n-
pepe-the-frog
NORMAL
2024-04-02T01:24:14.856064+00:00
2024-04-02T01:24:14.856082+00:00
4,053
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n- Convert each character to an integer, which is the appearance order in the string\n- For example,\n - `egg` to `0, 1, 1`\n - `add` to `0, 1, 1`\n - `foo` to `0, 1, 1`\n - `bar` to `0, 1, 2`\n - `paper` to `0, 1, 0, 2, 3`\n - `title` to `0, 1, 0, 2, 3`\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- map `s` to `i` and `t` to `j`\n- compare `s` and `t` after mapping\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n // time/space: O(n)/O(1)\n bool isIsomorphic(string s, string t) {\n // map `s` to `i` and `t` to `j`\n unordered_map<char, int> s2i, t2j;\n for (auto& c : s) {\n if (s2i.count(c) != 0) continue;\n s2i[c] = s2i.size();\n }\n for (auto& c : t) {\n if (t2j.count(c) != 0) continue;\n t2j[c] = t2j.size();\n }\n\n // compare `s` and `t` after mapping\n for (int i = 0; i < s.size(); i++) {\n if (s2i[s[i]] != t2j[t[i]]) return false;\n }\n return true;\n }\n};\n```
11
0
['Hash Table', 'C++']
4
isomorphic-strings
✅Java Simple Solution
java-simple-solution-by-ahmedna126-iqgi
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
ahmedna126
NORMAL
2023-11-14T11:44:12.066942+00:00
2023-11-14T11:44:12.066974+00:00
1,356
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nimport java.util.Hashtable;\nclass Solution {\n public static boolean isIsomorphic(String s, String t) {\n if (s.length() != t.length()) return false;\n\n Hashtable<Character , Character> hashtable = new Hashtable<>();\n for (int i = 0; i < s.length(); i++) \n {\n char c1 = s.charAt(i);\n char c2 = t.charAt(i);\n \n if (hashtable.containsKey(c1))\n {\n if (hashtable.get(c1) != c2) return false;\n }else {\n if (hashtable.containsValue(c2)) return false;\n hashtable.put(c1 , c2);\n }\n }\n\n return true;\n }\n}\n```\n\n\n## For additional problem-solving solutions, you can explore my repository on GitHub: [GitHub Repository](https://github.com/ahmedna126/java_leetcode_challenges)\n\n![abcd1.jpeg](https://assets.leetcode.com/users/images/b178e39e-2c88-42af-9c97-6aa1924db0a7_1699961197.5443523.jpeg)\n\n
11
0
['Java']
1
isomorphic-strings
Python fast and simple code
python-fast-and-simple-code-by-lukehwang-bbtx
python\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n z = zip(s, t)\n return len(set(s)) == len(set(t)) == len(set(z))\n
lukehwang
NORMAL
2022-09-30T14:25:15.296622+00:00
2022-09-30T14:25:15.296667+00:00
2,106
false
```python\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n z = zip(s, t)\n return len(set(s)) == len(set(t)) == len(set(z))\n```
11
0
['Python']
5
isomorphic-strings
c++(0ms 100%) very easy, hash table, one pass (with comments)
c0ms-100-very-easy-hash-table-one-pass-w-uo6s
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Isomorphic Strings.\nMemory Usage: 6.9 MB, less than 88.81% of C++ online submissions for Isomo
zx007pi
NORMAL
2021-01-05T18:34:22.195421+00:00
2022-07-28T16:20:19.369662+00:00
2,220
false
Runtime: 0 ms, faster than 100.00% of C++ online submissions for Isomorphic Strings.\nMemory Usage: 6.9 MB, less than 88.81% of C++ online submissions for Isomorphic Strings.\n\n```\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n int sind[129] = {0}, tind[129] = {0}; //hash tables for characters from our strings\n \n for(int i = 0; i < s.size(); i++)\n if( sind[s[i]] != tind[t[i]] ) return false; //if previous characters have different position\n else sind[s[i]] = tind[t[i]] = i+1; //put last position of characters\n \n return true;\n }\n};\n```
11
0
['C', 'C++']
3
isomorphic-strings
Fastest JavaScript Solution w/ Map & Set
fastest-javascript-solution-w-map-set-by-knqg
Strategy: Store each letter in t as the value of a key === to the letter in s at the same index, also add the character at this index of t to a set to ensure di
trevh
NORMAL
2020-03-04T00:18:49.773765+00:00
2020-03-04T18:26:10.266596+00:00
2,007
false
**Strategy**: Store each letter in *t* as the value of a key === to the letter in *s* at the same index, also add the character at this index of *t* to a set to ensure different keys can\'t map to the same letter, as that wouldn\'t be an isomorph\n```\nconst isIsomorphic = (s, t) => {\n let map = new Map(), set = new Set()\n for(let i = 0; i < s.length; i++){\n let sChar = s[i], tChar = t[i]\n if(map.has(sChar)){\n if(map.get(sChar) !== tChar)return false\n }else{\n if(set.has(tChar))return false\n map.set(sChar, tChar)\n set.add(tChar)\n }\n }\n return true\n};\n```
11
0
['JavaScript']
1
isomorphic-strings
Golang easy way to solve
golang-easy-way-to-solve-by-cra2yk-2gbq
using two maps to record last index.\n\ngolang\nfunc isIsomorphic(s string, t string) bool {\n\tsPattern, tPattern := map[uint8]int{}, map[uint8]int{}\n\tfor in
cra2yk
NORMAL
2019-06-24T08:18:04.532609+00:00
2019-09-02T07:49:58.693264+00:00
1,218
false
using two maps to record last index.\n\n```golang\nfunc isIsomorphic(s string, t string) bool {\n\tsPattern, tPattern := map[uint8]int{}, map[uint8]int{}\n\tfor index := range s {\n\t\tif sPattern[s[index]] != tPattern[t[index]] {\n\t\t\treturn false\n\t\t} else {\n\t\t\tsPattern[s[index]] = index + 1\n\t\t\ttPattern[t[index]] = index + 1\n\t\t}\n\t}\n\n\treturn true\n}\n```
11
0
['Go']
2
isomorphic-strings
AC HashMap Clear code (JAVA)
ac-hashmap-clear-code-java-by-zwangbo-fo6t
public class Solution {\n public boolean isIsomorphic(String s, String t) {\n if(s == null || t == null){\n return false;\n
zwangbo
NORMAL
2015-04-29T02:59:09+00:00
2015-04-29T02:59:09+00:00
4,530
false
public class Solution {\n public boolean isIsomorphic(String s, String t) {\n if(s == null || t == null){\n return false;\n }\n if(s.length() == 0 || t.length() == 0){\n return true;\n }\n \n Map<Character,Character> corr = new HashMap<Character,Character>();\n for(int i = 0; i < s.length(); i ++){\n char sc = s.charAt(i);\n char tc = t.charAt(i);\n if(corr.containsKey(sc)){\n if(corr.get(sc) != tc){\n return false;\n }\n }\n else{\n if(corr.containsValue(tc)){\n return false; \n }\n else{\n corr.put(sc,tc);\n }\n }\n }\n return true;\n }\n }
11
1
['Java']
5
isomorphic-strings
C++ || O(N) || Easy to Understand with In-Depth Explanation and Examples
c-on-easy-to-understand-with-in-depth-ex-spbd
Table of Contents\n\n- TL;DR\n - Code\n - Complexity\n- In Depth Analysis\n - Intuition\n - Approach\n - Example\n\n# TL;DR\n\nCreate a map of every charac
krazyhair
NORMAL
2022-12-06T20:59:32.742093+00:00
2023-01-03T15:54:03.014908+00:00
697
false
#### Table of Contents\n\n- [TL;DR](#tldr)\n - [Code](#code)\n - [Complexity](#complexity)\n- [In Depth Analysis](#in-depth-analysis)\n - [Intuition](#intuition)\n - [Approach](#approach)\n - [Example](#example)\n\n# TL;DR\n\nCreate a map of every character in `s` and `t` to an index (1-indexed) and ensure that the indicies are the same as we iterate through the strings\n\n## Code\n\n```c++\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n const int n = s.size();\n unordered_map<char,int> s_to_t_map;\n unordered_map<char,int> t_to_s_map;\n for (int i = 0; i < n; i++) {\n if (s_to_t_map[s[i]] != t_to_s_map[t[i]])\n return false;\n \n s_to_t_map[s[i]] = t_to_s_map[t[i]] = i + 1;\n }\n\n return true;\n }\n};\n```\n\n## Complexity\n\n**Time Complexity:** $$O(N)$$\n**Space Complexity:** $$O(N)$$\n\n**PLEASE UPVOTE IF YOU FIND MY POST HELPFUL!! \uD83E\uDD7A\uD83D\uDE01**\n\n---\n\n# In Depth Analysis\n\n## Intuition\n\nAn isomorphism is when you can map:\n* Every character of s onto only one character in t\n* Every character of t onto only one character in s\n\nIn other words, we need to make sure that in the example `s = "egg"` and `t = "add"` that:\n* From $$s \\rightarrow t$$, these characters map to each other: $$e \\rightarrow a$$\n* From $$t \\rightarrow s$$, these characters map to each other: $$e \\rightarrow a$$\n\nBUT opposed to mapping $$char \\rightarrow char$$, we will map $$char \\rightarrow int$$ since it will keep the same functionality\n\n## Approach \n\nCreate 2 unordered maps with the key value pair of `<char,int>`. One will be the mappings of the characters of $$s \\rightarrow index$$ and the other will be the mappings of the characters in $$t \\rightarrow index$$\n\nFor every character, we check the maps to ensure that they have the same index. If they don\'t, then we know that there is not a bijection from $$s \\leftrightarrow t$$ so we return false. Note that when we use `unordered_map` and the `[]` operator, if a key doesn\'t exist in a table yet, it will automatically create the key value pair and initialize the value to `0` since we are dealing with integers. We want this behavior since we are storing all of the mappings using 1-indexing and `0` would indicate that a character has not been mapped yet\n\nOtherwise, we update the map to have the index `i + 1` since we want to keep track of the latest value\n\n## Example\n\nLets use the second example, where `s = "foo"` and `t = "bar"`\n\n* i = 0\n\n`s_to_t_map[\'f\']` and `t_to_s_map[\'b\']` will have the same value of `0` since neither character has been mapped yet\n\nWe then assign both of them to have the value `1`: `s_to_t_map[\'f\'] = t_to_s_map[\'b\'] = 1`\n\n* i = 1\n\n`s_to_t_map[\'o\']` and `t_to_s_map[\'a\']` will have the same value of `0` since neither character has been mapped yet\n\nWe then assign both of them to have the value `2`: `s_to_t_map[\'o\'] = t_to_s_map[\'a\'] = 2`\n\n* i = 2\n\n`s_to_t_map[\'o\'] = 2` from the previous iteration but `t_to_s_map[\'r\'] = 0` since it hasn\'t been mapped yet. Since these two values are different, it shows that there is not a bijection since `\'o\'` would be mapped two 2 different characters in `t` (mapped to both `\'a\'` and `\'r\'`), so we return false\n\n**PLEASE UPVOTE IF YOU FIND MY POST HELPFUL!! \uD83E\uDD7A\uD83D\uDE01**
10
0
['Hash Table', 'String', 'C++']
1
isomorphic-strings
Kotlin In One Line.
kotlin-in-one-line-by-cityzouitel-f20j
kotlin\nval isIsomorphic: (String, String) -> Boolean = { s, t ->\n s.zip(t).toSet().size.run { equals(s.toSet().size) && equals(t.toSet().size) }\n}\n
CityZouitel
NORMAL
2022-11-15T09:46:51.265698+00:00
2022-11-15T09:50:46.694355+00:00
757
false
```kotlin\nval isIsomorphic: (String, String) -> Boolean = { s, t ->\n s.zip(t).toSet().size.run { equals(s.toSet().size) && equals(t.toSet().size) }\n}\n```
10
0
['Kotlin']
1
isomorphic-strings
HashMap simple O(n) Javascript ES6
hashmap-simple-on-javascript-es6-by-mp33-jha6
Commentary:\n- Key idea is to ignore the char-matching but map the pattern via index-footprints\n\nconst isIsomorphic = function(s, t) {\n const hash1 = {}\n
mp3393
NORMAL
2021-05-18T01:40:42.066712+00:00
2021-05-18T01:41:01.921270+00:00
962
false
`Commentary:`\n- Key idea is to ignore the char-matching but map the pattern via index-footprints\n```\nconst isIsomorphic = function(s, t) {\n const hash1 = {}\n const hash2 = {}\n for(let idx = 0; idx < s.length; idx++){\n\t\tif(hash1[s[idx]] !== hash2[t[idx]]) return false\n hash1[s[idx]] = idx\n hash2[t[idx]] = idx \n }\n return true\n};\n```
10
0
['JavaScript']
4
isomorphic-strings
C++ 3 lines
c-3-lines-by-votrubac-nuwm
We map characters in each string to the last position it occurred. Then we check that next character in two strings occurred in the same position.\n\nNote that
votrubac
NORMAL
2019-03-03T21:43:01.683667+00:00
2019-03-03T21:43:01.683752+00:00
650
false
We map characters in each string to the last position it occurred. Then we check that next character in two strings occurred in the same position.\n\nNote that newly appeared characters are mapped to zero initially, so they will always match.\n\nExample for "eggnog" and "addend":\n```\n1. ms[\'e\'] == mt[\'a\'] == 0, ms[\'e\'] = mt[\'a\'] = 1;\n2. ms[\'g\'] == mt[\'d\'] == 0, ms[\'g\'] = mt[\'d\'] = 2;\n3. ms[\'g\'] == mt[\'d\'] == 2, ms[\'g\'] = mt[\'d\'] = 3;\n4. ms[\'n\'] == mt[\'e\'] == 0, ms[\'n\'] = mt[\'e\'] = 4;\n5. ms[\'o\'] == mt[\'n\'] == 0, ms[\'o\'] = mt[\'n\'] = 5;\n6. ms[\'g\'] == mt[\'d\'] == 3, ms[\'g\'] = mt[\'d\'] = 6;\n```\n\n```\nbool isIsomorphic(string s, string t) {\n int ms[128] = {}, mt[128] = {}, n = s.size(), i = 0;\n for (; i < n && ms[s[i]] == mt[t[i]]; ++i) ms[s[i]] = mt[t[i]] = i + 1;\n return i == n;\n}\n```
10
0
[]
0
isomorphic-strings
✅ Easiest 😎 FAANG Method Ever !!! 💥
easiest-faang-method-ever-by-adityabhate-ap6o
\n\n# \uD83D\uDCCC Complexity :-\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n- Space complexity: O(n)\n Add your space complexity he
AdityaBhate
NORMAL
2022-12-23T17:16:10.757220+00:00
2022-12-23T17:16:10.757255+00:00
8,246
false
\n\n# \uD83D\uDCCC Complexity :-\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# \uD83D\uDCCC Code :- Using 2 Unordered Maps\n```\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n unordered_map<char,char> mp1;\n unordered_map<char,char> mp2;\n int i,j;\n if(s.size()!=t.size())\n return 0;\n for(i=0;i<s.size();){\n if((mp1[s[i]] && mp1[s[i]]!=t[i]) || (mp2[t[i]] && mp2[t[i]]!=s[i])){\n return 0;\n } \n else {\n mp1[s[i]]=t[i];\n mp2[t[i]]=s[i];\n i++;\n }\n }\n return 1;\n }\n};\n```
9
0
['Hash Table', 'String', 'C++', 'Java', 'Python3']
6
isomorphic-strings
easiest solution || c-plus-plus || map || easy to understand
easiest-solution-c-plus-plus-map-easy-to-xkk6
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time
youdontknow001
NORMAL
2022-11-20T05:00:45.127518+00:00
2022-11-20T05:00:45.127554+00:00
1,781
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n map<char,char> mp,mp1;\n int i=0,j=0;\n while(i<s.length() && j<t.length()){\n if(!mp.count(s[i]) && !mp1.count(t[j])){\n mp[s[i]]=t[j];\n mp1[t[j]]=s[i];\n }else{\n if(mp[s[i]]!=t[j] || mp1[t[j]]!=s[i]) return false;\n }\n i++;j++;\n }\n return true;\n }\n};\n```
9
0
['C++']
1
isomorphic-strings
C# Dictionary Simple Solution
c-dictionary-simple-solution-by-gregskly-72w2
\npublic class Solution \n{\n public bool IsIsomorphic(string s, string t) \n {\n var dict = new Dictionary<char, char>();\n for(int i = 0 ;
gregsklyanny
NORMAL
2022-11-01T08:42:35.772463+00:00
2022-12-12T15:43:07.862160+00:00
2,213
false
```\npublic class Solution \n{\n public bool IsIsomorphic(string s, string t) \n {\n var dict = new Dictionary<char, char>();\n for(int i = 0 ; i < s.Length; i++)\n {\n char ss = s[i];\n char st = t[i];\n if(dict.ContainsKey(ss))\n {\n if(st != dict[ss]) return false;\n } else \n {\n if(dict.ContainsValue(st)) return false;\n dict.Add(ss, st);\n }\n }\n return true;\n }\n}\n```
9
0
['C#']
2
isomorphic-strings
Java Solution using Hashmaps
java-solution-using-hashmaps-by-manisha0-2lyd
Runtime: 22 ms, faster than 28.64% of Java online submissions for Isomorphic Strings.\nMemory Usage: 42.9 MB, less than 67.91% of Java online submissions for Is
manisha04
NORMAL
2022-09-16T09:11:51.731718+00:00
2022-09-16T09:11:51.731754+00:00
1,379
false
**Runtime: 22 ms, faster than 28.64% of Java online submissions for Isomorphic Strings.\nMemory Usage: 42.9 MB, less than 67.91% of Java online submissions for Isomorphic Strings.\n**\n*If this solution was helpful to you , please upvote it*\n```\nclass Solution {\n public boolean isIsomorphic(String s, String t) {\n \n if(s.length()==t.length()){\n LinkedHashMap<Character, Character> smap=new LinkedHashMap();\n LinkedHashMap<Character, Character> tmap=new LinkedHashMap();\n for(int i=0;i<s.length();i++){\n if(!smap.containsKey(s.charAt(i))) smap.put(s.charAt(i),t.charAt(i));\n if(!tmap.containsKey(t.charAt(i))) tmap.put(t.charAt(i),s.charAt(i));\n }\n for(int i=0;i<t.length();i++){\n if(tmap.get(t.charAt(i)) != s.charAt(i) || smap.get(s.charAt(i)) != t.charAt(i)) return false;\n } \n }\n else return false;\n \n return true;\n }\n}\n```
9
0
['Java']
2
isomorphic-strings
Java Solution from pratik
java-solution-from-pratik-by-pratik_pati-4c53
Solution 1: Brute Force Approach\n\nIntuition:\n- Two strings s and t are called isomorphic:\n\t- If there is a one to one mapping possible for every character
pratik_patil
NORMAL
2019-02-15T15:52:01.366728+00:00
2021-10-24T05:29:24.004335+00:00
1,175
false
**Solution 1: Brute Force Approach**\n\n**Intuition:**\n- Two strings `s` and `t` are called **isomorphic**:\n\t- If there is a one to one mapping possible for every character of `s` to every character of `t`, and\n\t- If all occurrences of every character in `s` map to same character in `t`\n- A **brute-force** solution is to consider every character of `s` and check if all occurrences of it map to same character in `t`. For example, `s = "egg"` and `t = "add"`, the mapping could be `\'e\' -> \'a\'` and `\'g\' -> \'d\'`. Time complexity of this solution is `O(N * N)`.\n\n**Time complexity:** O(N<sup>2</sup>), since `containsValue()` method takes `O(N)` time and it will be called `N` times.\n**Space Complexity:** `O(1)`\n\n```\nclass Solution {\n public boolean isIsomorphic(String s, String t) {\n Map<Character, Character> map = new HashMap<>();\n\n if (s.length() != t.length()) {\n return false;\n }\n\n for (int i = 0; i < s.length(); i++) {\n char a = s.charAt(i);\n char b = t.charAt(i);\n\n if (map.containsKey(a) && !map.get(a).equals(b) || !map.containsKey(a) && map.containsValue(b)) {\n return false;\n } else {\n map.put(a, b);\n }\n }\n return true;\n }\n}\n```\n\n**Solution 2: Optimized Approach**\n\n**Intuition:**\n- The **better idea** is, instead of directly mapping `\'e\'` to `\'a\'`, another way is to mark them with same value, for example, `\'e\' -> 1`, `\'a\'-> 1`, and `\'g\' -> 2`, `\'d\' -> 2`, this approach works in linear time.\n\n**Algorithm:**\n- Initialize two integer arrays `A` and `B`, to store the character mappings of strings `s` and `t`.\n- Traverse the characters of both `s` and `t` on the same position. \n- If their mapping values in arrays `A` and `B` are different, means the mapping is incorrect and `false` is returned. If not so, then mapping is created.\n- Initially both arrays `A` and `B` will be initialized to `zero` , so we need to use a different value when `i == 0` and that is why so `i + 1` is preferred.\n\n**Time complexity:** `O(N)`\n**Space Complexity:** `O(1)`\n\n```\nclass Solution {\n public boolean isIsomorphic(String s, String t) {\n int[] A = new int[256];\n int[] B = new int[256];\n\n if (s.length() != t.length()) {\n return false;\n }\n\n for (int i = 0; i < s.length(); i++) {\n char c1 = s.charAt(i);\n char c2 = t.charAt(i);\n\n if (A[c1] != B[c2]) {\n return false;\n }\n\n A[c1] = i + 1;\n B[c2] = i + 1;\n }\n return true;\n }\n}\n```
9
0
[]
0
isomorphic-strings
3 lines solution for C
3-lines-solution-for-c-by-snowleo-2ple
bool isIsomorphic(char* s, char* t) {\n for (int i = 0; i < strlen (s); i++)\n if ((strchr (s,s[i]) - s) != (strchr(t,t[i]) - t)) return false;\n
snowleo
NORMAL
2015-12-09T14:05:30+00:00
2015-12-09T14:05:30+00:00
872
false
bool isIsomorphic(char* s, char* t) {\n for (int i = 0; i < strlen (s); i++)\n if ((strchr (s,s[i]) - s) != (strchr(t,t[i]) - t)) return false;\n return true;\n }
9
0
[]
1
isomorphic-strings
2 map logic
2-map-logic-by-sushilmaxbhile-m422
ApproachMaintain 2 maps and store {s[idx]: t[idx]} and {t[idx]: s[idx]} and check if key value pairs are not duplicate as well as key value pair availableCompl
sushilmaxbhile
NORMAL
2025-03-21T10:46:56.574380+00:00
2025-03-21T10:46:56.574380+00:00
90
false
# Approach Maintain 2 maps and store {s[idx]: t[idx]} and {t[idx]: s[idx]} and check if key value pairs are not duplicate as well as key value pair available # Complexity - Time complexity: 5 ms Beats 18.01% - Space complexity: 4.56 MB Beats 65.88% # Code ```golang [] func isIsomorphic(s string, t string) bool { if len(s) != len(t) { return false } sm, tm := map[byte]byte{}, map[byte]byte{} for idx := 0; idx < len(s); idx++ { if sv, ok := sm[s[idx]]; ok && sv != t[idx] { return false } else { sm[s[idx]]= t[idx] } if tv, ok := tm[t[idx]]; ok && tv != s[idx] { return false } else { tm[t[idx]]= s[idx] } } return true } ```
8
0
['Go']
0
isomorphic-strings
✅Easy✨||C++|| Beats 100% || With Explanation ||
easyc-beats-100-with-explanation-by-olak-l4zo
Intuition\n Describe your first thoughts on how to solve this problem. \nThe intuition checks if two strings, s and t, are isomorphic by ensuring a one-to-one c
olakade33
NORMAL
2024-04-02T11:00:29.073055+00:00
2024-04-02T11:00:29.073088+00:00
1,078
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition checks if two strings, s and t, are isomorphic by ensuring a one-to-one correspondence between each character in s and t using two hash maps. It iterates through both strings simultaneously, verifying existing mappings for consistency and creating new mappings when necessary. If it encounters an inconsistency or a character in t already mapped to another character in s, it returns false.\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Initialization: Two hash maps (unordered_map in C++) mapS2T and mapT2S are initialized. These maps store the character mappings from s to t and from t to s, respectively.\n\n2. Iteration: The algorithm iterates through each character in the strings s and t simultaneously, using an index i.\n\n3. Mapping Validation:\n\n. For each character charS in s at index i, the algorithm checks if . there is an existing mapping in mapS2T.\n . If there is an existing mapping, it checks if charS is correctly mapped to charT (the character in t at the same index). If not, the strings are not isomorphic, and the function returns false.\n. If there is no existing mapping for charS, it checks if charT is already mapped to a different character in mapT2S. If so, this means that charT is expected to map to two different characters, which violates the one-to-one mapping rule, and the function returns false.\n4. Creating New Mappings: If the checks pass, it means the current characters charS and charT can be mapped to each other. The algorithm then adds these new mappings to mapS2T and mapT2S.\n\n5. Completion: If the algorithm successfully iterates through all characters without returning false, it means that all character mappings are valid, and the strings are isomorphic. The function then returns true.\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(N), where N is the length of the strings. The algorithm iterates through each character of the strings exactly once. The operations within each iteration (accessing and updating the hash maps) are on average constant time, O(1), thanks to the nature of unordered_map in C++. Thus, the overall time complexity is linear in the size of the input strings.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(N), in the worst case. This is because, in the worst-case scenario, each character in the strings s and t could be different, requiring each character to be stored in both mapS2T and mapT2S. However, since the domain of characters (for example, ASCII characters) is limited, this space complexity could also be considered O(1) in practice if the character set is fixed and limited in size.\n\n\n# Code\n```\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n \n unordered_map<char, char> mapS2T;\n unordered_map<char, char> mapT2S;\n \n for (int i = 0; i < s.size(); ++i) {\n char charS = s[i];\n char charT = t[i];\n \n // Check if there\'s a mapping for charS in mapS2T and if it maps to the same character in t\n if (mapS2T.find(charS) != mapS2T.end()) {\n if (mapS2T[charS] != charT) {\n return false;\n }\n } else { // If no mapping exists, check if charT is already mapped to some other character in mapT2S\n if (mapT2S.find(charT) != mapT2S.end()) {\n return false;\n }\n \n // Create new mapping since it\'s valid\n mapS2T[charS] = charT;\n mapT2S[charT] = charS;\n }\n }\n \n return true;\n }\n};\n```
8
0
['C++']
0
isomorphic-strings
Python one liner | Using set and zip with explanation 🔥🔥🔥
python-one-liner-using-set-and-zip-with-k0qyo
Intuition\nTo determine if two strings s and t are isomorphic, we need to establish a one-to-one mapping between characters in s and characters in t. One way to
Saketh3011
NORMAL
2024-04-02T00:16:15.826311+00:00
2024-04-02T00:17:57.407083+00:00
864
false
# Intuition\nTo determine if two strings `s` and `t` are isomorphic, we need to establish a one-to-one mapping between characters in `s` and characters in `t`. One way to approach this is to check if the number of unique characters in `s` and `t` are the same and also if the number of unique mappings between characters of `s` and `t` are the same.\n\n# Approach\nWe can achieve this by converting `s` and `t` into sets to get unique characters and then zip them together to create pairs of corresponding characters. Finally, we check if the lengths of these sets are equal. If they are equal, it indicates that each character in `s` uniquely maps to a character in `t`, satisfying the isomorphic condition.\n\n# Complexity\n- **Time complexity:** O(n), where n is the length of the strings `s` and `t`. Converting the strings to sets and zipping them together both take linear time in terms of the length of the strings.\n \n- **Space complexity:** O(n), where n is the length of the strings `s` and `t`. This is because we create sets of characters from the strings, which could potentially contain all characters from the strings, and zipping the strings also requires additional space for the resultant tuples. However, the space used is linear with respect to the input size.\n\n# Code\n```python\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n return len(set(s)) == len(set(t)) == len(set(zip(s, t)))\n
8
0
['Python', 'Python3']
0
isomorphic-strings
C++ Optimal Solution
c-optimal-solution-by-pryansh-94cb
Intuition\n Describe your first thoughts on how to solve this problem. \nlet understand it by considering an example for say\n> str1: aax\nstr2: tty\n\nso what
pryansh_
NORMAL
2023-08-04T06:42:14.670545+00:00
2023-08-04T06:42:14.670589+00:00
1,285
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nlet understand it by considering an example for say\n> ***str1***: aax\n***str2***: tty\n\nso what if I map `"a"` against `"t"` and then everytime before inserting another pair `{key, value}` into the map I will check that whether the key i.e. `"a"` has already occured before? and if yes then is the value against `"a"` is same as the value which is occuring now in str2 ? which is `true` here since the value is really the same everytime against the char `"a"` which is `"t"`.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nProblem is somewhat vague and many of us get tricked by the statement `"No two characters may map to the same character"` but what it does state is that for a pair of string namely str1 and str2 both need to be isomorphic to each other and not just one.\n\n**Example:** \n> ***str1***: badc\n***str2***: baba\nso here you might have though that str1 is isomorphic to str2 but in fact str2 also needs to be isomorphic to str1 and since its not, thus we return ***false***.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(2n) at worst case\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n if(s.length() != t.length()) return false; // if lengths are not the same then they can\'t be Isomorphic.\n \n unordered_map<char, char> mps; // mark chars from str1 to str2\n unordered_map<char, char> mpt; // mark chars from str2 to str1\n for(int i = 0; i < s.length(); i++) {\n /* if s[i] already occured in mps then if its not mapped to whats now in t[i] then it means we have something like\n a -> p\n a -> t instead of \'p\' thus return false\n Similarly we check that if\n a -> p\n p -> t instead of \'a\' thus return false */\n if(mps[s[i]] && mps[s[i]] != t[i]) return false;\n if(mpt[t[i]] && mpt[t[i]] != s[i]) return false;\n /* then map s[i] and t[i] as key, value pairs\n if they didn\'t occur in map or if they occured then they did follow the rules of being isomorphic */\n mps[s[i]] = t[i];\n mpt[t[i]] = s[i];\n }\n return true;\n }\n};\n```\n<h2> \nIf It really helped you or gave you the intuition then kindly do consider upvoting my response. It motivates me to keep posting these solutions. </h2>\n\n![ta duh.jpg](https://assets.leetcode.com/users/images/64ecd495-a6f7-468c-bdb9-0940ad69d54b_1691131160.8898883.jpeg)\n
8
0
['String', 'C++']
1
isomorphic-strings
Python3 One Liner beats 95.93% with Proof
python3-one-liner-beats-9593-with-proof-64lj0
Explanation \n\n- zip function pairs the first item of the first String with first item of the second String.\n\ns = "egg"\nt = "add"\n\nset(zip(s,t) = {(\'e\',
quibler7
NORMAL
2023-04-19T09:11:46.837477+00:00
2023-04-19T09:11:46.837516+00:00
1,231
false
# Explanation \n\n- `zip` function pairs the first item of the first String with first item of the second String.\n```\ns = "egg"\nt = "add"\n\nset(zip(s,t) = {(\'e\', \'a\'), (\'g\', \'d\')}\n```\nThis was in case when two strings are Isomorphic.\n\nLet\'s see for the string when they are not Isomorphic :\n```\ns = "egk"\nt = "add"\n\nset(zip(s,t) = {(\'e\', \'a\'), (\'g\', \'d\'), (\'k\', \'d\')}\n```\nHere length 2 == 2 == 3 is False so the answer becomes false. \n\n# Code\n```\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n return len(set(s)) == len(set(t)) == len(set(zip(s,t))) \n```\n# Proof \n![Screenshot 2023-04-19 at 2.31.42 PM.png](https://assets.leetcode.com/users/images/0f2d929a-8e48-460d-9284-3e04f98a39e0_1681894917.271043.png)\n
8
0
['String', 'Python', 'Python3']
2
isomorphic-strings
Scala simple solution
scala-simple-solution-by-xdavidrtx-kgfr
\n def isIsomorphic(s: String, t: String): Boolean = {\n val mapped = s.zip(t).toMap.map(_.swap)\n t.flatMap(mapped.get(_)).mkString == s\n}\n\n
xDavidRTx
NORMAL
2022-09-09T15:47:46.940654+00:00
2022-09-09T15:47:46.940747+00:00
213
false
```\n def isIsomorphic(s: String, t: String): Boolean = {\n val mapped = s.zip(t).toMap.map(_.swap)\n t.flatMap(mapped.get(_)).mkString == s\n}\n```\n
8
0
['Scala']
0
isomorphic-strings
Mapless TypeScript Solution - 100% Memory
mapless-typescript-solution-100-memory-b-j0n5
To minimize memory usage, we can eliminate the need to create maps. Instead of tracking what characters map to we can make sure that for each position in the st
WAB2
NORMAL
2022-07-04T22:48:55.351941+00:00
2022-07-04T22:48:55.351988+00:00
1,161
false
To minimize memory usage, we can eliminate the need to create maps. Instead of tracking what characters map to we can make sure that for each position in the strings the first occurrence of the current character matches for both s and t.\n\n```typescript\nfunction isIsomorphic(s: string, t: string): boolean {\n // isomorphic strings always have the same length\n if (s.length != t.length) {\n return false;\n }\n for (let i = 1; i < s.length; i++) {\n // verify that the first occurrence of the current character occurs at the same position in both s and t\n if (t.indexOf(t[i]) !== s.indexOf(s[i])) {\n return false;\n }\n }\n return true;\n}\n```\n
8
1
['TypeScript']
5
isomorphic-strings
Easy Mapping C++
easy-mapping-c-by-tusharkhanna575-yp19
\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n if(s.size()!=t.size())\n {\n return 0;\n }\n c
tusharkhanna575
NORMAL
2022-06-21T14:51:56.813425+00:00
2022-06-21T14:51:56.813467+00:00
1,322
false
```\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n if(s.size()!=t.size())\n {\n return 0;\n }\n char map_s[128]={0};\n char map_t[128]={0};\n int length=s.size();\n for(int i=0;i<length;i++)\n {\n if(map_s[s[i]]!=map_t[t[i]])\n {\n return 0;\n }\n map_s[s[i]]=i+1;\n map_t[t[i]]=i+1;\n }\n return 1;\n }\n};\n```
8
0
['C', 'C++']
0
isomorphic-strings
Python single line beats 97%
python-single-line-beats-97-by-diksha_ch-r5jr
\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool: \n return len(set(s))==len(set(t))==len(set(zip(s,t)))\n \n
diksha_choudhary
NORMAL
2021-12-16T05:06:45.712236+00:00
2021-12-16T05:06:45.712279+00:00
855
false
```\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool: \n return len(set(s))==len(set(t))==len(set(zip(s,t)))\n \n```
8
0
['Python', 'Python3']
1
isomorphic-strings
[Python] 2 dicts solution, explained
python-2-dicts-solution-explained-by-dba-33mj
Go symbol by symbol and add direct and inverse connections to hash tables d1 and d2.\n1. If i not in d1 and j in d2, it means, that something is wrong, we have
dbabichev
NORMAL
2021-07-12T08:17:16.036293+00:00
2021-07-12T08:17:16.036327+00:00
455
false
Go symbol by symbol and add direct and inverse connections to hash tables `d1` and `d2`.\n1. If `i not in d1` and `j in d2`, it means, that something is wrong, we have case `a -> x`, `b -> x`, return `False`.\n2. If `i not in d1` and `j not in d2`, it means that we see this pair first time, update both dictionaries.\n3. If `i in d1` and `d1[i] != j`, it means, that we have `a -> x`, `a -> y`, return `False`.\n4. In the end return `True` if we did not return anyghing before.\n\n#### Complexity\nTime complexity is `O(n)`, space complexity is `O(m)`, where `m` is size of alphabet to keep dictionaries.\n\n#### Code\n```python\nclass Solution:\n def isIsomorphic(self, s, t):\n d1, d2 = {}, {}\n for i, j in zip(s,t):\n if i not in d1:\n if j in d2: return False\n else:\n d1[i] = j\n d2[j] = i\n elif d1[i] != j: return False\n \n return True\n```\n\nIf you have any questions, feel free to ask. If you like solution and explanations, please **Upvote!**
8
0
['Hash Table']
1
isomorphic-strings
Python3 - one-liner with index
python3-one-liner-with-index-by-the_snow-0nef
```\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n \n return [s.index(ch) for ch in s] == [t.index(ch) for ch in t]\n
the_snow
NORMAL
2021-03-25T13:17:02.077925+00:00
2021-03-25T13:24:36.174226+00:00
621
false
```\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n \n return [s.index(ch) for ch in s] == [t.index(ch) for ch in t]\n
8
0
['Python']
0
isomorphic-strings
C++ 8 ms beats 67.75% one path, two mapping arrays
c-8-ms-beats-6775-one-path-two-mapping-a-x3nh
\tbool isIsomorphic(string s, string t)\n\t{\n\t\tvector mapStoT(127, 0);\n\t\tvector mapTtoS(127, 0);\n\t\tint len = s.length();\n\t\t\n\t\tfor (int i = 0; i <
petrik
NORMAL
2016-05-20T20:34:53+00:00
2016-05-20T20:34:53+00:00
1,916
false
\tbool isIsomorphic(string s, string t)\n\t{\n\t\tvector<char> mapStoT(127, 0);\n\t\tvector<char> mapTtoS(127, 0);\n\t\tint len = s.length();\n\t\t\n\t\tfor (int i = 0; i < len; ++i)\n\t\t{\n\t\t\tchar s_char = s[i], t_char = t[i];\n\t\t\tif (mapStoT[s_char] == 0 && mapTtoS[t_char] == 0)\n\t\t\t{\n\t\t\t\tmapStoT[s_char] = t_char;\n\t\t\t\tmapTtoS[t_char] = s_char;\n\t\t\t}\n\t\t\telse if (mapTtoS[t_char] != s_char || mapStoT[s_char] != t_char)\n\t\t\t{\n\t\t\t\treturn false;\n\t\t\t}\n\t\t}\n\n\t\treturn true;\n\t}
8
1
[]
2
isomorphic-strings
Easiest Beginner Friendly Approach
easiest-beginner-friendly-approach-by-am-1bd6
✅ Explaination of the Code: Pehle size compare kiya, agar s aur t ka size alag hai, to directly false return kar diya. Pehle loop me sabhi characters ko ~ se
aman8558
NORMAL
2025-03-31T02:12:42.695013+00:00
2025-04-02T12:06:39.633009+00:00
739
false
# **✅ Explaination of the Code:** 1. Pehle size compare kiya, agar s aur t ka size alag hai, to directly false return kar diya. 2. Pehle loop me sabhi characters ko ~ se initialize kiya. 3. Dusre loop me: - Agar s[i] map me pehli baar aa raha hai (m[s[i]] == '~'), to uska mapping t[i] se kar diya. - Agar already mapped hai, to check kiya ki existing mapping t[i] se match karti hai ya nahi. 4. Same logic p map pe bhi lagaya to ensure bi-directional mapping. # Complexity - Time complexity: O(N) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(N) <!-- Add your space complexity here, e.g. $$O(n)$$ --> ![400a6c24-9fb8-4388-b4b3-677cc5dd0d8b_1742947844.4592059.png](https://assets.leetcode.com/users/images/8d5076ec-969a-470d-9724-cbfcd977db87_1743387091.2598944.png) # Code ```cpp [] class Solution { public: bool isIsomorphic(string s, string t) { int n = s.size(); int x = t.size(); if( x != n ) return false; unordered_map< char,char >m; unordered_map< char,char >p; for( int i = 0 ; i < n ; i++ ){ m[ s[i] ] = '~'; p[ t[i] ] = '~'; } char temp1; char temp2; for( int i = 0 ; i < n ; i++ ){ if( m[ s[i] ] == '~' ) m[ s[i] ] = t[i]; else{ temp1 = m[ s[i] ]; if( temp1 != t[i] ) return false; } if( p[ t[i] ] == '~' ) p[ t[i] ] = s[i]; else{ temp2 = p[ t[i] ] ; if( temp2 != s[i] ) return false; } } return true; } }; ```
7
0
['Hash Table', 'String', 'C++']
2
isomorphic-strings
🧩✨ Python Solution | Isomorphic Strings | ⚡ 99% Runtime | 📦 O(n) Space 💡
python-solution-isomorphic-strings-99-ru-z2d9
Intuition\n Describe your first thoughts on how to solve this problem. \nThe problem requires checking if two strings s and t are isomorphic, meaning each chara
LinhNguyen310
NORMAL
2024-08-12T16:55:59.975515+00:00
2024-08-12T16:55:59.975536+00:00
652
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires checking if two strings s and t are isomorphic, meaning each character in s can be replaced to get t, with no two characters mapping to the same character, except possibly to itself.\n\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nCharacter Mapping: We use two dictionaries, sMap and tMap, to keep track of the positions of each character in s and t.\nPattern Formation: For each character, store its index in the respective map.\nComparison: After building the maps, extract and sort the index lists for each string.\nEquality Check: Compare the sorted index lists to determine if the strings have the same pattern of character positions.\n# Complexity\n- Time complexity:O(nlogn) (due to sorting), where n is the length of the strings.\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(n) to store the indices of characters in the dictionaries.\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution(object):\n def isIsomorphic(self, s, t):\n """\n :type s: str\n :type t: str\n :rtype: bool\n """\n # no two character might map to the same character, a character might map to itself\n n, m = len(s), len(t)\n if n != m:\n return False\n\n tMap, sMap = {}, {}\n tCount, sCount = [], []\n\n def helper(currentMap):\n ret = []\n for key, value in currentMap.items():\n ret.append(value)\n ret.sort()\n return ret\n\n for i in range(n):\n sLetter, tLetter = s[i], t[i]\n if sLetter not in sMap:\n sMap[sLetter] = [i]\n else:\n sMap[sLetter] += [i]\n\n if tLetter not in tMap:\n tMap[tLetter] = [i]\n else:\n tMap[tLetter] += [i]\n\n tCount, sCount = helper(tMap), helper(sMap)\n return tCount == sCount\n```\n\n![cute_dinosaur_cooie.jpg](https://assets.leetcode.com/users/images/47d82413-9472-49f3-8f48-4b2e660bbafd_1723481738.9861064.jpeg)\n
7
0
['Hash Table', 'String', 'Python', 'Python3']
0
isomorphic-strings
Best/Easiest Java Solution🔥
besteasiest-java-solution-by-thepriyansh-ab4f
Intuition\nThe idea is to iterate through each character of both strings simultaneously and maintain mappings between characters of string s and characters of s
thepriyanshpal
NORMAL
2024-04-02T04:11:22.110697+00:00
2024-04-02T04:11:22.110718+00:00
1,086
false
# Intuition\nThe idea is to iterate through each character of both strings simultaneously and maintain mappings between characters of string s and characters of string t. We use two hash maps to keep track of mappings in both directions (from s to t and from t to s). At each step, we check if the current characters in s and t are already mapped. If they are, we verify if the mappings are consistent. If not, we update the mappings. If any inconsistency is found during the process, we conclude that the strings are not isomorphic.\n\n# Approach\n1. Check if the lengths of strings s and t are equal. If not, they cannot be isomorphic, so return false.\n2. Create two hash maps: sToT to store mappings from characters of string s to characters of string t, and tToS to store mappings from characters of string t to characters of string s.\n3. Iterate through each character of strings s and t.\n4. For each character at position i, check if it\'s already mapped in both directions.\n - If a character in s is already mapped to a different character in t, or vice versa, return false.\n - If the character is not yet mapped, add the mapping to both hash maps.\n5. If all characters are successfully mapped without any conflicts, return true.\n\n# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\n public boolean isIsomorphic(String s, String t) {\n //Check if both the strings are equal\n if(s.length()!=t.length()){\n return false;\n }\n\n //Create two hash maps to store the mappings from s to t and from t to s\n HashMap<Character, Character> sToT = new HashMap<>();\n HashMap<Character, Character> tToS = new HashMap<>();\n\n //Iterate through each character in the strings\n for(int i = 0; i<s.length(); i++){\n char charS = s.charAt(i);\n char charT = t.charAt(i);\n\n //Check if the character in s has already been mapped to a different character in t\n if(sToT.containsKey(charS)){\n if(sToT.get(charS)!=charT){\n return false;\n }\n }else{\n //If not, then map the character in s to the character in t\n sToT.put(charS, charT);\n }\n\n //Check if the character in t has been already mapped to a different character in s\n if (tToS.containsKey(charT)){\n if(tToS.get(charT)!=charS){\n return false;\n }\n }else{\n //If npt then map the character in t to the character in s\n tToS.put(charT, charS);\n }\n }\n //If all the characters are mapped without any confilicts, return true\n return true;\n }\n}\n```
7
0
['Java']
3
isomorphic-strings
beats 100% || learn intuition building
beats-100-learn-intuition-building-by-ab-u0lm
Intuition\n Describe your first thoughts on how to solve this problem. \n# pls upvote guys \n# Approach\n Describe your approach to solving the problem. \nAbsol
Abhishekkant135
NORMAL
2024-04-02T03:40:21.754525+00:00
2024-04-02T03:40:21.754556+00:00
1,334
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n# pls upvote guys \n# Approach\n<!-- Describe your approach to solving the problem. -->\nAbsolutely, here\'s a breakdown of the code that determines if two strings `s` and `t` are isomorphic:\n\n**Functionality:**\n\n- It checks if two strings are isomorphic, meaning the characters in `s` can be replaced with another set of characters to obtain `s`. However, the order of the characters should be preserved, and no two characters in `s` can map to the same character in `t`.\n\n**Steps:**\n\n1. **Initialization:**\n - `int[] mapping = new int[256]`: Creates an array `mapping` to store character mappings from `s` to `t`. Each index represents a character (ASCII values are typically used). A value of 0 indicates no mapping yet for that character in `s`.\n - `boolean[] mapped = new boolean[256]`: Creates a boolean array `mapped` to track if a character in `t` has already been used as a replacement for a character in `s`.\n\n2. **Iterating Through Strings:**\n - The `for` loop iterates through each corresponding character `i` in strings `s` and `t`:\n - **Checking for Unmapped Characters in `s`:**\n - `if (mapping[charS] == 0)`: This checks if the current character `charS` from `s` hasn\'t been mapped yet (represented by a 0 in the `mapping` array).\n - `if (mapped[charT])`: If the corresponding character `charT` in `t` has already been used as a replacement for another character in `s` (checked by `mapped[charT]`), this indicates a violation of the isomorphism rule. The function returns `false`.\n - If both conditions are not met, it proceeds with mapping.\n - `mapping[charS] = charT`: Stores the mapping between `charS` and `charT` in the `mapping` array.\n - `mapped[charT] = true`: Marks `charT` as used in the `mapped` array to prevent future mismatches.\n - **Checking for Consistent Mappings:**\n - `else`: If `charS` has already been mapped (not the first occurrence), it checks if the existing mapping in `mapping[charS]` matches the current `charT`.\n - `if (mapping[charS] != charT)`: If the existing mapping doesn\'t match the current `charT`, it indicates an inconsistency in the character replacements. The function returns `false`.\n\n3. **Returning the Result:**\n - After iterating through all characters, if no inconsistencies were found, the function returns `true`, indicating that the strings are isomorphic.\n\n**Key Points:**\n\n- The code uses two arrays to efficiently track character mappings and usage.\n- It ensures that each character in `s` maps to a unique character in `t` and vice versa (one-to-one mapping).\n- It handles the case where a character might appear multiple times in `s`.\n\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n- Time Complexity: O(n), where n is the length of the strings `s` and `t`. This is due to the single loop iterating through the characters.\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n- Space Complexity: O(1), as the size of the arrays (`mapping` and `mapped`) is constant (256) and independent of the input string lengths.\n# Code\n```\nclass Solution {\n public boolean isIsomorphic(String s, String t) {\n int[] mapping = new int[256];\n boolean[] mapped = new boolean[256]; // To check if a character in t has been mapped before\n \n for (int i = 0; i < s.length(); i++) {\n char charS = s.charAt(i);\n char charT = t.charAt(i);\n \n if (mapping[charS] == 0) { // If not mapped yet\n if (mapped[charT]) // If t[i] has been mapped before\n return false;\n mapping[charS] = charT;\n mapped[charT] = true;\n } else {\n if (mapping[charS] != charT)\n return false;\n }\n }\n return true;\n }\n}\n\n```
7
0
['Array', 'Java']
5
isomorphic-strings
Mapping Characters to check for Structural Equality
mapping-characters-to-check-for-structur-wd6x
Intuition\n Describe your first thoughts on how to solve this problem. \n1) The code aims to determine whether two strings s and t are isomorphic, meaning that
harshsri1602
NORMAL
2024-04-02T00:59:08.080684+00:00
2024-04-02T00:59:08.080703+00:00
68
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1) The code aims to determine whether two strings s and t are isomorphic, meaning that each character in s can be replaced with another character in t while preserving the order.\n2) To achieve this, the code maps each character in both strings to a unique integer representing its relative position of appearance.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1) Initialize two unordered maps, m1 and m2, to store mappings of characters to integers for strings s and t respectively.\n2) Initialize two vectors, v1 and v2, to store the mapped integers for characters in strings s and t.\n3) Iterate through each character in string s.\n> If the character is not found in m1, assign it a unique integer a and insert the mapping into m1. \n>>Append the mapped integer to vector v1.\n4) Repeat the same process for string t, using m2, b, and v2.\nCompare vectors v1 and v2. If they are equal, return true; otherwise, return false.\n\n# Explaination \n1) By mapping characters to integers based on their relative positions of appearance, the code effectively captures the structural pattern of the strings.\n2) If two strings are isomorphic, their mapped integer sequences will be identical.\n3) Utilizing unordered maps ensures efficient retrieval of mapped integers with constant time complexity.\n\n# Complexity\n- Time complexity: O(N) , N is number of characters in the string\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n- Space complexity: O(M) , M is the sum of unique characters in both s and t\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n // we will compare the base structure of both the strings\n\n // basically ,all we are doing is that in each of the vectors v1 and v2 , we are storing the relative positions of each character \n\n // eg : s = add\n //v1=[1,2,2]\n // eg : s = aad\n //v1=[1,1,2]\n\n // if t = egg\n // v2=[1,2,2]\n\n // All in all , if a character has appeared before, then insert the first the associated \'a\' or \'b\' with it\n\n // we are using an unordered map since we can retieve a value in O(1) in contrast to a map, which would take O(log n)\n unordered_map<char,int>m1,m2;\n vector<int>v1,v2;\n int a=1,b=1;\n for(int i=0;i<s.length();i++){\n char ch = s[i];\n if(m1.find(ch) == m1.end()){\n m1.insert(make_pair(ch,a));\n a++;\n }\n v1.push_back(m1[ch]);\n }\n for(int i=0;i<t.length();i++){\n char ch = t[i];\n if(m2.find(ch) == m2.end()){\n m2.insert(make_pair(ch,b));\n b++;\n }\n v2.push_back(m2[ch]);\n }\n\n return (v1 == v2);\n }\n};\n```
7
1
['Hash Table', 'String', 'C++']
0
isomorphic-strings
Simple and detailed explanation using hashmap
simple-and-detailed-explanation-using-ha-obd2
Intuition\nWe need to establish bidirectional mappings between characters in the two strings to check if they are isomorphic. By using two unordered maps, we ca
fruity_226
NORMAL
2024-03-03T18:18:45.562484+00:00
2024-03-03T18:18:45.562535+00:00
1,632
false
# Intuition\nWe need to establish bidirectional mappings between characters in the two strings to check if they are isomorphic. By using two unordered maps, we can track these mappings and return `false` if any inconsistency is found; otherwise, we return `true`.\n\n# Approach\n- `Initialize Maps:` Start by creating two unordered maps to store mappings between characters of both strings.\n- `Iterate Through Characters:` Loop through characters of both strings simultaneously.\n- `Mapping Creation:` If a character in one string has not been mapped yet, create a mapping to its counterpart character in the other string.\n- `Consistency Check:` If a mapping already exists, ensure it remains consistent; if not, return `false` immediately.\n- `Return Result:` After iterating through all characters without encountering any inconsistencies, return `true`, indicating the strings are isomorphic.\n\n# Complexity\n- *Time complexity:*\n`O(n)`, where n is the length of the input strings. This is because we iterate through both strings simultaneously, and the length of the input strings determines the number of iterations.\n\n- *Space complexity:*\n`O(min(m, n))`, where m and n are the number of unique characters in both the strings respectively. In the worst case, where all characters are unique, the space complexity is O(n) for the maps. However, it\'s constrained by the size of the alphabet (m), making it O(min(m, n)).\n\n\n# Code\n```\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n unordered_map<char,char> m1,m2;\n int i=0,j=0;\n while(i<s.length() and j<t.length()){\n if(!m1.count(s[i]) and !m2.count(t[j])){\n m1[s[i]]=t[j];\n m2[t[j]]=s[i];\n }\n else{\n if(m1[s[i]]!=t[j] or m2[t[j]]!=s[i]) return false;\n }\n i++;j++;\n }\n return true;\n }\n};\n```
7
0
['C++']
2
isomorphic-strings
C++ easy solution | Beats 100% | Hash Table | Optimised approach
c-easy-solution-beats-100-hash-table-opt-ag1g
Please upvote to motivate me to write more solutions.\n\n\n\nIntuition\nApproach\nComplexity\nTime complexity:\nO(|str1|+|str2|).\n\nSpace complexity:\nO(Number
Kanishq_24je3
NORMAL
2024-01-10T18:44:19.832478+00:00
2024-01-10T18:44:19.832499+00:00
1,630
false
# Please upvote to motivate me to write more solutions.\n\n\n\nIntuition\nApproach\nComplexity\nTime complexity:\nO(|str1|+|str2|).\n\nSpace complexity:\nO(Number of different characters).\n\n\n# Code\n```\nclass Solution {\npublic:\n bool isIsomorphic(string s, string t) {\n if (s.size() != t.size()) {\n return false;\n }\n int hash[256] = {0};\n bool isMapped[256] = {0};\n\n for (int i = 0; i < s.size(); i++) {\n if (hash[s[i]] == 0 && !isMapped[t[i]]) {\n hash[s[i]] = t[i];\n isMapped[t[i]] = true;\n }\n }\n\n for (int i = 0; i < s.size(); i++) {\n if (hash[s[i]] != t[i]) {\n return false;\n }\n }\n\n return true;\n }\n};\n\n\n\n\n```
7
0
['Hash Table', 'String', 'C++']
0
isomorphic-strings
✅|||🔥🔥Faster than 93%🔥🔥|||Simple and easy python solution with explanation ✅✅✅🔥
faster-than-93simple-and-easy-python-sol-4n4t
PLEASE UPVOTE IT TAKES A LOT OF TIME AND EFFORT TO MAKE THIS\n\n# Intuition\nThe goal is to determine if two strings, s and t, are isomorphic. Two strings are c
user0517qU
NORMAL
2024-01-10T04:54:55.678558+00:00
2024-01-10T04:54:55.678592+00:00
1,157
false
# PLEASE UPVOTE IT TAKES A LOT OF TIME AND EFFORT TO MAKE THIS\n\n# Intuition\nThe goal is to determine if two strings, s and t, are isomorphic. Two strings are considered isomorphic if there exists a one-to-one mapping of characters from one string to the other.\n\n# Approach\nTo solve this problem, we can use two dictionaries (mapping_s_t and mapping_t_s) to keep track of the mapping between characters of s to t and vice versa. We iterate through each character in both strings simultaneously and check if the mappings are consistent in both directions.\n\n- Initialize two empty dictionaries, mapping_s_t and mapping_t_s.\n- Iterate through each character pair (char_s, char_t) in the corresponding positions of s and t.\n- Check if char_s is already in mapping_s_t. If it is, ensure that its mapping is consistent with char_t.\n- Check if char_t is already in mapping_t_s. If it is, ensure that its mapping is consistent with char_s.\n- If either check fails, return False as the strings are not isomorphic.\n- If the iteration completes without any inconsistencies, return True as the strings are isomorphic.\n# Complexity\n- Time complexity: O(n)\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution:\n def isIsomorphic(self, s: str, t: str) -> bool:\n mapping_s_t = {}\n mapping_t_s = {}\n\n if len(s) != len(t):\n return False\n\n for char_s, char_t in zip(s, t):\n if char_s in mapping_s_t:\n if mapping_s_t[char_s] != char_t:\n return False\n else:\n mapping_s_t[char_s] = char_t\n\n if char_t in mapping_t_s:\n if mapping_t_s[char_t] != char_s:\n return False\n else:\n mapping_t_s[char_t] = char_s\n\n return True\n\n\n```
7
0
['Python3']
0
isomorphic-strings
C# - Hash Map O(n) with Explanation
c-hash-map-on-with-explanation-by-vflawl-3ckx
Intuition\nTo determine if two strings, s and t, are isomorphic, we need to check if we can replace the characters in s with the characters in t while preservin
vFlawless
NORMAL
2023-05-06T13:32:12.166407+00:00
2023-05-08T14:51:56.685196+00:00
1,113
false
# Intuition\nTo determine if two strings, `s` and `t`, are isomorphic, we need to check if we can replace the characters in `s` with the characters in `t` while preserving the order of characters. This implies a one-to-one mapping between characters of `s` and `t`. We can utilize a hash map to keep track of the mappings and verify if they satisfy the isomorphic condition.\n\n# Approach\n1. Initialize two hash maps, `sToT` and `tToS`, to store the mappings from characters of `s` to `t` and from `t` to `s`, respectively.\n2. Iterate through each character in `s` and `t` simultaneously using a loop.\n3. For each character pair `(sChar, tChar)`:\n - Check if `sChar` exists as a key in `sToT` and `tChar` exists as a key in `tToS`.\n - If both mappings exist, compare the stored values in `sToT[sChar]` and `tToS[tChar]`.\n - If the values are not equal, return `false` as the characters cannot be mapped consistently.\n - If only one of the mappings exists, return `false` as the characters cannot be mapped consistently.\n - If neither mapping exists:\n - Add `sChar` as a key with a value of `tChar` in `sToT`.\n - Add `tChar` as a key with a value of `sChar` in `tToS`.\n4. If the loop completes without returning `false`, return `true` as the strings `s` and `t` are isomorphic.\n\n# Complexity\n- Time complexity: O(n), where n is the length of the strings `s` and `t`. We iterate through the characters of both strings once.\n- Space complexity: O(n), where n is the length of the strings `s` and `t`. In the worst case, the hash maps can store all distinct characters from both strings.\n\n# Code\n```\npublic class Solution {\n public bool IsIsomorphic(string s, string t) {\n if (s.Length != t.Length)\n return false;\n \n Dictionary<char, char> sToT = new Dictionary<char, char>();\n Dictionary<char, char> tToS = new Dictionary<char, char>();\n \n for (int i = 0; i < s.Length; i++)\n {\n char sChar = s[i];\n char tChar = t[i];\n \n if (sToT.ContainsKey(sChar))\n {\n if (sToT[sChar] != tChar)\n return false;\n }\n else if (tToS.ContainsKey(tChar))\n {\n if (tToS[tChar] != sChar)\n return false;\n }\n else\n {\n sToT[sChar] = tChar;\n tToS[tChar] = sChar;\n }\n }\n \n return true;\n }\n}\n\n```
7
0
['C#']
1
isomorphic-strings
Easy to understand Java Solution Using HashMap data structure (Explained !!!) 💡
easy-to-understand-java-solution-using-h-3j2r
Approach\n- char to char comparision between two strings using two different Hashmaps due to the nature of the datastructure.\n\n# Complexity\n- Time complexity
AbirDey
NORMAL
2023-04-17T15:09:41.847367+00:00
2023-04-17T15:09:41.847413+00:00
441
false
# Approach\n- char to char comparision between two strings using two different Hashmaps due to the nature of the datastructure.\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n# Code\n```\nclass Solution {\n public boolean isIsomorphic(String s, String t) {\n \n // Two Hashmaps for verifying Isomorphism both ways\n \n HashMap <Character, Character> map = new HashMap<>();\n HashMap <Character, Character> map2 = new HashMap<>();\n\n // Due to the Nature of HashMap functionality, it only focuses one way relation, that is key ---> value and not key <---> value\n\n //This for loop if for Isomorphism from String s to String t\n\n if(s.length()!=t.length()){\n return false;\n }\n \n for(int i = 0;i<s.length();i++){\n if(map.containsKey(s.charAt(i))){\n if(t.charAt(i) != map.get(s.charAt(i))){\n\n // If one character returns a different value then the one stored, return false\n return false;\n }\n }else{\n\n // Storing unique character to character values that not ahve appeared yet \n map.put(s.charAt(i),t.charAt(i));\n }\n\n }\n\n // Isomorphism from String t to String s\n\n for(int i = 0;i<t.length();i++){\n if(map2.containsKey(t.charAt(i))){\n if(s.charAt(i) != map2.get(t.charAt(i))){\n return false;\n }\n }else{\n map2.put(t.charAt(i),s.charAt(i));\n }\n\n }\n\n // If the false conditions do not meet, return true, i.e., Isomorphic string\n\n return true;\n }\n}\n```\n\n![images.jpeg](https://assets.leetcode.com/users/images/73649a3a-1481-4d48-bba1-f14d2443645b_1681744138.8248034.jpeg)\n
7
0
['Hash Table', 'String', 'Java']
1
isomorphic-strings
Well Explained Code || 2 HashMaps used in JAVA✅
well-explained-code-2-hashmaps-used-in-j-sfkk
\n\n# Approach\nThis code is an implementation of a solution to determine if two strings, s and t, are isomorphic. Two strings are considered isomorphic if the
sakshamkaushiik
NORMAL
2023-02-10T08:42:01.417698+00:00
2023-02-10T08:42:01.417744+00:00
547
false
\n\n# Approach\nThis code is an implementation of a solution to determine if two strings, s and t, are isomorphic. Two strings are considered isomorphic if the characters in one string can be replaced to get the other string.\n\nThe approach used in this solution is to use two HashMaps, map1 and map2. map1 maps each character in string s to its corresponding character in string t. map2 is used to check if a character in string t has already been mapped to a character in string s.\n\nThe function first checks if the lengths of the two strings are equal. If not, the function returns false, as isomorphic strings must have the same length.\n\nFor each character in string s, the function retrieves the corresponding character in string t from map1. If the character is already in map1, the function checks if the value in map1 for that character is equal to the character in string t at the same position. If the values are not equal, the function returns false, as the two strings are not isomorphic.\n\nIf the character is not in map1, the function checks if the character in string t has already been mapped to a character in string s using map2. If it has, the function returns false, as the two strings are not isomorphic. If the character has not been mapped, the function adds the mapping to map1 and marks the character in string t as being mapped in map2.\n\nThe function continues this process for each character in string s until all characters have been checked. If all the characters have been checked and no conflicts have been found, the function returns true, as the two strings are isomorphic.\n\n# Complexity\n- Time complexity:\nThe time complexity of this solution is O(n), where n is the length of the strings. This is because, in the worst case, all characters in the strings need to be checked once, so the number of operations is proportional to the length of the strings.\n\n\n- Space complexity:\nThe space complexity of this solution is O(n), as each character in the strings can be mapped to a different character, and the HashMaps can store at most n entries.\n\n\n\n# Code\n```\nclass Solution {\n public boolean isIsomorphic(String s, String t) {\n if(s.length()!= t.length()){\n return false;\n }\n HashMap<Character,Character> map1 = new HashMap<>();\n HashMap<Character,Boolean> map2 = new HashMap<>();\n for(int i=0;i<s.length();i++){\n char ch1 = s.charAt(i);\n char ch2 = t.charAt(i);\n if(map1.containsKey(ch1)==true){\n if(map1.get(ch1)!= ch2){\n return false;\n }\n }else{\n if(map2.containsKey(ch2)==true){\n return false;\n }else{\n map1.put(ch1,ch2);\n map2.put(ch2,true);\n }\n }\n }\n return true;\n }\n}\n```\n![upvote.jpeg](https://assets.leetcode.com/users/images/4861c23d-8de7-40b5-b6c4-9adfa1490602_1676018490.8380122.jpeg)\n
7
0
['Hash Table', 'Java']
1
isomorphic-strings
[Python] Easy Hash Table solution, beats 95%
python-easy-hash-table-solution-beats-95-q95o
\u2705 Upvote if it helps !\n\n# Approach\n Describe your approach to solving the problem. \n- If the sizes of "s" and "t" aren\'t equal, return False\n- I used
jean_am
NORMAL
2023-01-15T12:29:09.062191+00:00
2023-02-14T08:58:57.798961+00:00
2,499
false
### \u2705 Upvote if it helps !\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- If the sizes of *"s"* and *"t"* aren\'t equal, ```return False```\n- I used a **Hash Table** called *"equivalence"* in order to track if a character in *"s"* has always the same equivalent character in *"t"*.\n - For example:\n - If we have a ```b``` at index 0 and 2 in *"s"*.\n - And if ```equivalence[\'b\'] == \'c\'```.\n - We have to have ```c``` at index 0 and 2 in *"t"*.\n- **But** we also have to check if 2 keys in *"equivalence"* have the same value. \n - If it\'s the case, it means that we don\'t have an isomorphic string because we don\'t have a **symetric** equivalence in the characters of the two strings.\n - It means that a character in *"t"* hasn\'t always the same equivalent character in *"s"*.\n - That\'s why I used a ```set()``` called ```already_mapped```.\n \n\n# Code\n```\nclass Solution(object):\n def isIsomorphic(self, s, t):\n if len(s) != len(t): return False\n equivalence = {}\n already_mapped = set()\n\n for c_s, c_t in zip(s, t):\n if c_s in equivalence and c_t != equivalence[c_s]:\n return False\n if c_s not in equivalence:\n if c_t in already_mapped:\n return False\n equivalence[c_s] = c_t \n already_mapped.add(c_t)\n\n \n return True\n\n```
7
0
['Hash Table', 'Python']
1
minimum-increments-for-target-multiples-in-an-array
DP WITH BITMASK ✅✅✅Easy To Understand C++ Code
dp-with-bitmask-easy-to-understand-c-cod-5cj1
IntuitionKey Insight Each element in target must have at least one multiple in nums. Instead of treating each target element individually, we can group them
insane_prem
NORMAL
2025-02-02T04:07:44.187230+00:00
2025-02-02T06:50:39.161373+00:00
3,647
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Key Insight - Each element in target must have at least one multiple in nums. - Instead of treating each target element individually, we can group them into subsets and find the least common multiple (LCM) for each subset. This helps us determine the smallest number that can satisfy multiple target elements at once. # Approach <!-- Describe your approach to solving the problem. --> 1. Precompute LCM for All Subsets: - We iterate through all possible subsets of target using bitmasking. - For each subset, we calculate the LCM of the elements in that subset. - The LCM represents the smallest number that is a multiple of all elements in the subset. - We store the LCM for each subset in a map (mpp), where the key is the bitmask representing the subset. Example: If target = [4, 5, 6], then: For bitmask 011 (subset [4, 5]), the LCM is 20. For bitmask 111 (subset [4, 5, 6]), the LCM is 60. 2. Dynamic Programming to Track Minimum Operations: - We use a DP array (dp) where each index represents a bitmask (subset of target). - dp[mask] stores the minimum number of operations required to satisfy all target elements in the subset represented by mask. - Initialize dp[0] = 0 because no operations are needed for an empty subset. - For each number in nums, we update the DP array: --- - For each subset (bitmask), we calculate the cost of making the current number a multiple of the subset's LCM. - If the current number is already a multiple, the cost is 0; otherwise, the cost is the difference between the LCM and the remainder of the number divided by the LCM. - We update the DP array to reflect the minimum operations required for each subset. 3. Final Result: - The answer is found in dp[fullmask], where fullmask represents the subset containing all target elements. - If dp[fullmask] is still INT_MAX, it means it’s impossible to satisfy all target elements, so we return -1. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { long long lcm(long long a, long long b) { return a / __gcd(a, b) * b; } public: int minimumIncrements(vector<int>& nums, vector<int>& target) { long long k = target.size(); unordered_map<long long, long long> mpp; for (long long mask = 1; mask < (1 << k); mask++) { vector<long long> subset; for (long long i = 0; i < k; i++) { if (mask & (1 << i)) { subset.push_back(target[i]); } } long long currlcm = subset[0]; for (long long j = 1; j < subset.size(); j++) { currlcm = lcm(currlcm, subset[j]); } mpp[mask] = currlcm; } long long fullmask = (1 << k) - 1; vector<long long> dp(1 << k, INT_MAX); dp[0] = 0; for (auto num : nums) { vector<pair<long long, long long>> maskcost; for (auto& entry : mpp) { long long mask = entry.first; long long lcmval = entry.second; long long rm = num % lcmval; long long cost = (rm == 0) ? 0 : (lcmval - rm); maskcost.emplace_back(mask, cost); } vector<long long> newdp = dp; for (long long prevmask = 0; prevmask < (1 << k); prevmask++) { if (dp[prevmask] == INT_MAX) continue; for (auto& mc : maskcost) { long long mask = mc.first; long long cost = mc.second; long long nmask = prevmask | mask; long long ncost = dp[prevmask] + cost; if (ncost < newdp[nmask]) { newdp[nmask] = ncost; } } } dp = newdp; } return dp[fullmask] == INT_MAX ? -1 : dp[fullmask]; } }; ```
30
1
['Dynamic Programming', 'Bit Manipulation', 'Bitmask', 'C++']
7
minimum-increments-for-target-multiples-in-an-array
[Java/C++/Python] Easy and Concise | Beats 100% | Full Explanation
javacpython-easy-and-concise-by-_ashish_-v96k
Step-by-Step Explanation: Understanding the Problem: We are given two arrays: nums[]: Represents numbers we can modify. target[]: Contains numbers for whic
_Ashish_Lahane_
NORMAL
2025-02-02T05:18:10.471818+00:00
2025-02-02T06:15:09.815410+00:00
1,957
false
# **Step-by-Step Explanation**: 1. **Understanding the Problem**: We are given two arrays: - `nums[]`: Represents numbers we can modify. - `target[]`: Contains numbers for which we need to adjust elements in `nums` so that their LCM constraints are met. The goal is to **modify elements in** `nums[]` by incrementing them to make them **multiples of LCMs of subsets of** `target[]` while minimizing the total increment cost. --- 2. **Using Bitmasking to Represent Subsets**: - Since `target` has `m` elements, we can represent its subsets using a **bitmask of size** `m`. - `1 << m` represents `2^m` subsets. - Example for `m = 3` (`target = [a, b, c]`): `000` → Empty set `{}`. `001` → `{c}` `010` → `{b}` `011` → `{b, c}` `100` → `{a}` `111` → `{a, b, c}` (full set). Each subset is represented as a bitmask, where: - `1` means the element is included. - `0` means it is not included. --- 3. **Precomputing LCMs for Subsets**: - We compute the LCM of each subset of `target` and store it in `lcmArr[mask]`. - This allows us to quickly access LCM values when updating the DP table. Example for `target = [3, 4, 6]`: ``` Mask (Binary) Subset LCM `001` {6} 6 `010` {4} 4 `011` {4,6} 12 `100` {3} 3 `101` {3,6} 6 `111` {3,4,6} 12 ``` --- 4. **Using Dynamic Programming**: We define `dp[mask]` as the minimum cost to satisfy the subset `mask`. A. **Base Case**: - `dp[0] = 0` (No constraints, so no cost). - `dp[mask] = INF` for all other subsets. B. **Processing `nums[]` one by one**: - We create a new `newdp` array (copy of previous `dp`). - We iterate over each subset mask (from `1` to `2^m - 1`). - For each subset, we retrieve its `LCM`. - Compute how much we need to increment `x` to make it a multiple of LCM. - Update DP: Merge this subset with previous subsets and store the minimum cost. --- 5. **Transition Formula**: For each `x` in `nums`: - Compute remainder `r = x % L` - Compute increment cost: - If `r == 0`, `cost = 0` - Else, `cost = L - r` (increment `x` to the next multiple of `L`) - Update `dp[newMask]`: ```` newdp[newMask] = Math.min(newdp[newMask], dp[old] + cost); ```` - Where `newMask = old | mask` (merging subsets). --- 6. **Final Answer**: - The answer is `dp[fullMask]`, where `fullMask = (1 << m) - 1`, representing the subset `{a, b, c, ..., m}`. - This is the minimum cost needed to satisfy **all** conditions. --- 7. **Time Complexity Analysis**: - Precompute LCM for subsets → `O(m * 2^m)` - Iterate over nums → `O(n * 2^m * 2^m)` - Total Complexity: `O(n * m * 2^m)`, feasible for `m ≤ 10`. --- 8. **Example Walkthrough**: ``` Input: nums = [6, 12, 15] target = [3, 4, 6] ``` **Bitmask Representation of** `target`: ``` Mask Subset LCM `001` {6} 6 `010` {4} 4 `011` {4,6} 12 `100` {3} 3 `101` {3,6} 6 `111` {3,4,6} 12 ``` **Processing** `nums[]`: 1. Processing `6` - It’s already a multiple of `3` and `6`. - It needs `+2` to become a multiple of `4`. - Update `dp` accordingly. 2. Processing `12` - It’s a multiple of `4`, `3`, and `6` → No change needed. 3. Processing `15` - Needs `+3` to become a multiple of `3`, `6`, `4`. - Update `dp` accordingly. --- **Summary** - **We use bitmasking** to represent subsets of `target`. - **We precompute LCM** values to optimize lookup. - **We use DP** to track the minimum cost to adjust `nums[]`. - **The final answer is in** `dp[fullMask]`, which stores the minimum cost to satisfy all constraints. --- # Code ```java [] class Solution { public int minimumIncrements(int[] nums, int[] target) { int m = target.length; int fullMask = (1 << m) - 1; long[] lcmArr = new long[1 << m]; for (int mask = 1; mask < (1 << m); mask++) { long L = 1; for (int j = 0; j < m; j++) { if ((mask & (1 << j)) != 0) { L = lcm(L, target[j]); } } lcmArr[mask] = L; } long INF = Long.MAX_VALUE / 2; long[] dp = new long[1 << m]; for (int i = 0; i < (1 << m); i++) { dp[i] = INF; } dp[0] = 0; for (int x : nums) { long[] newdp = dp.clone(); for (int mask = 1; mask < (1 << m); mask++) { long L = lcmArr[mask]; long r = x % L; long cost = (r == 0 ? 0 : L - r); for (int old = 0; old < (1 << m); old++) { int newMask = old | mask; newdp[newMask] = Math.min(newdp[newMask], dp[old] + cost); } } dp = newdp; } return (int) dp[fullMask]; } private long gcd(long a, long b) { return b == 0 ? a : gcd(b, a % b); } private long lcm(long a, long b) { return a / gcd(a, b) * b; }} ``` ``` C++ [] class Solution { public: int minimumIncrements(vector<int>& nums, vector<int>& target) { int m = target.size(); int fullMask = (1 << m) - 1; // All bits set (for subset representation) vector<long long> lcmArr(1 << m); // Precompute LCM for each subset of `target` for (int mask = 1; mask < (1 << m); mask++) { long long L = 1; for (int j = 0; j < m; j++) { if (mask & (1 << j)) { L = lcm(L, target[j]); } } lcmArr[mask] = L; } long long INF = LLONG_MAX / 2; vector<long long> dp(1 << m, INF); dp[0] = 0; // No target selected yet, so cost is 0 for (int x : nums) { vector<long long> newdp = dp; for (int mask = 1; mask < (1 << m); mask++) { long long L = lcmArr[mask]; long long r = x % L; long long cost = (r == 0 ? 0 : L - r); // Adjusting x to be a multiple of L // Update DP array for (int old = 0; old < (1 << m); old++) { int newMask = old | mask; // Merge current subset with previous subsets newdp[newMask] = min(newdp[newMask], dp[old] + cost); } } dp = newdp; } return (int)dp[fullMask]; // Minimum cost to satisfy all LCM conditions } private: long long gcd(long long a, long long b) { return b == 0 ? a : gcd(b, a % b); } long long lcm(long long a, long long b) { return a / gcd(a, b) * b; } }; ``` ``` Python [] class Solution: def minimumIncrements(self, nums, target): m = len(target) full_mask = (1 << m) - 1 # All subsets represented as bitmasks # Precompute LCM for each subset of `target` lcm_arr = [0] * (1 << m) for mask in range(1, 1 << m): L = 1 for j in range(m): if mask & (1 << j): L = self.lcm(L, target[j]) lcm_arr[mask] = L INF = float('inf') dp = [INF] * (1 << m) dp[0] = 0 # Base case: No elements selected, so cost is 0 for x in nums: new_dp = dp[:] for mask in range(1, 1 << m): L = lcm_arr[mask] r = x % L cost = 0 if r == 0 else L - r # Adjust x to be a multiple of L # Update DP array for old in range(1 << m): new_mask = old | mask # Merge current subset with previous subsets new_dp[new_mask] = min(new_dp[new_mask], dp[old] + cost) dp = new_dp return int(dp[full_mask]) # Minimum cost to satisfy all LCM conditions def lcm(self, a, b): return a * b // gcd(a, b) ```
14
1
['Dynamic Programming', 'Bitmask', 'Python', 'C++', 'Java']
3
minimum-increments-for-target-multiples-in-an-array
Combinations
combinations-by-votrubac-ez7h
Intuition We only have (up to) 4 elements in target. An element in nums could be a multiple of several elements from target. Approach Generate all combinations
votrubac
NORMAL
2025-02-02T04:23:05.717136+00:00
2025-02-02T04:46:31.429295+00:00
1,927
false
# Intuition 1. We only have (up to) 4 elements in `target`. 2. An element in `nums` could be a multiple of several elements from `target`. # Approach 1. Generate all combinations of target elements. - [4], [3, 1], [2, 2], [2, 1, 1], and [1, 1, 1, 1] - we can use `combinations` to do that. 2. For each combination, compute its `lcm`. 3. Identify the cheapest element to make it a multiple of `lcm`. # Code ```python3 [] class Solution: def minimumIncrements(self, nums: List[int], target: List[int]) -> int: def get_sum(t: set[int], idx: set[int]) -> int: res = inf for i in range(1, len(t) + 1): for cmb in combinations(t, i): lcm_cmb, id, res1 = lcm(*cmb), 0, inf for i, n in enumerate(nums): if i not in idx: multiple = lcm_cmb * ((n - 1) // lcm_cmb + 1) if res1 > multiple - n: res1 = multiple - n id = i res = min(res, res1 + get_sum(t - set(cmb), idx.union((id,)))) return 0 if res == inf else res return get_sum(set(target), set()) ```
13
1
['Python3']
2
minimum-increments-for-target-multiples-in-an-array
Striver approach take or nottake C++ Solution
striver-approach-take-or-nottake-c-solut-kfnv
IntuitionApproachComplexity Time complexity: Space complexity: Code
aero_coder
NORMAL
2025-02-03T10:38:57.259108+00:00
2025-02-03T10:42:57.821222+00:00
1,174
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { int n, m; const int mod = 1e9 + 7; vector<int> preComputedLCM; using ll = long long; void preComputeLCM(vector<int>& target) { int totalSubsets = 1 << m; preComputedLCM.assign(totalSubsets, 1); for (int mask = 1; mask < totalSubsets; mask++) { ll l = 1; for (int i = 0; i < m; i++) { if (mask & (1 << i)) { l = (l / __gcd(l, (ll)target[i])) * target[i]; if (l > mod) l = mod + 1; } } preComputedLCM[mask] = (l > mod ? mod + 1 : (int)l); } } vector<vector<int>> dp; int find(int ind, vector<int>& nums, vector<int>& target, int mask) { if (mask == 0) return 0; if (ind == n) return 1e9; if (dp[mask][ind] != -1) return dp[mask][ind]; int nottake = find(ind + 1, nums, target, mask); int take = 1e9; for (int subset = 1; subset < (1 << m); subset++) { if (subset & (1 << subset) == 0) continue; int curl = preComputedLCM[subset]; if (curl > mod) continue; ll cur = ceil(1.0 * nums[ind] / curl) * curl; if (cur > mod) continue; take = min(take, (int)(cur - nums[ind] + find(ind + 1, nums, target, mask ^ subset))); } return dp[mask][ind] = min(take, nottake); } public: int minimumIncrements(vector<int>& nums, vector<int>& target) { this->n = (int)nums.size(); this->m = (int)target.size(); preComputeLCM(target); int mask = (1 << m) - 1; dp.assign(mask + 1, vector<int>(n, -1)); return find(0, nums, target, mask); } }; ```
8
0
['Math', 'Dynamic Programming', 'C++']
1
minimum-increments-for-target-multiples-in-an-array
C++ | DP + BitMask | Explanation | With Intuition and Approach | Best Solution
c-dp-bitmask-explanation-with-intuition-qthkb
IntuitionThe problem appears to be finding the minimum total increments needed to make each number in nums divisible by at least one number in target. The use o
smitvavliya
NORMAL
2025-02-02T13:03:08.532797+00:00
2025-02-02T13:30:18.239726+00:00
531
false
# Intuition ###### The problem appears to be finding the minimum total increments needed to make each number in nums divisible by at least one number in target. The use of bitmasks suggests we need to track which target numbers we still need to consider for each position, and dynamic programming indicates we need to avoid recalculating overlapping subproblems. # Approach ### 1. State Representation : - We use a DP with two states: position and mask - position represents current index in nums array - mask is a binary representation where each bit represents whether we still need to make a number divisible by corresponding target value ### 2. Base Cases : - If mask becomes 0, we return 0 as we've satisfied all conditions - If we reach end of array (pos == n) and mask is not 0, return INT_MAX - If we reach end and mask is 0, return 0 ### 3. Recursive Logic : ``` // For each position, we have two choices: a) Skip current number (don't modify it) b) Modify current number to make it divisible by one or more target numbers ``` ### 4. For modification choice : - For each set bit in mask: - Calculate minimum increment needed (op) to make current number divisible by target[bit] - Create new mask by turning off bits for all targets that divide the modified number - Recursively solve for remaining positions with new mask - Take minimum of all possible choices ### 5. Memoization: - Store results in dp array to avoid recalculation - Key is (position, mask) pair # Complexity #### Time complexity: $$O(n * 2^m * m ^ 2)$$ - n = length of nums array - m = length of target array - For each position, we try all possible combinations in mask (2^m) - For each mask, we check m bits #### Space complexity: $$O(n * 2^m)$$ - DP table size is n * 2^m - Recursion stack depth can go up to n # Code ```cpp [] class Solution { public: int recursion(int pos, int mask, int n, int m, vector<int> &nums, vector<int> &target, vector<vector<int>> &dp) { if(mask == 0) return 0; if(pos == n) { return (mask == 0) ? 0 : INT_MAX; } if(dp[pos][mask] != -1) { return dp[pos][mask]; } int ans = recursion(pos + 1, mask, n, m, nums, target, dp); for(int bit = 0; bit < m; bit++) { if(1 & (mask >> bit)) { int q = ceil((double)nums[pos] / target[bit]); int op = q * target[bit] - nums[pos]; int newNum = nums[pos] + op; int newMask = mask; for(int i = 0; i < m; i++) { if((1 & (newMask >> i)) && (newNum % target[i] == 0)) { newMask -= (1 << i); } } int res = recursion(pos + 1, newMask, n, m, nums, target, dp); ans = min(ans, res == INT_MAX ? res : op + res); } } return dp[pos][mask] = ans; } int minimumIncrements(vector<int> &nums, vector<int> &target) { int n = nums.size(), m = target.size(); int mask = (1 << m) - 1; vector<vector<int>> dp(n, vector<int> (mask + 1, -1)); return recursion(0, mask, n, m, nums, target, dp); } }; ```
7
1
['Dynamic Programming', 'Memoization', 'Bitmask', 'C++']
1
minimum-increments-for-target-multiples-in-an-array
[Python3] mask dp
python3-mask-dp-by-ye15-dppt
IntuitionUse DP. Here, we define the states as (i, m) where i indicates the ith number in nums is being looked at and m is a bit mask whose set bits correspond
ye15
NORMAL
2025-02-02T04:03:32.455100+00:00
2025-02-02T06:24:53.594390+00:00
642
false
# Intuition Use DP. Here, we define the states as `(i, m)` where `i` indicates the `i`th number in `nums` is being looked at and `m` is a bit mask whose set bits correspond to the numbers in `target` whose multiple is already included. Here, `dp[i][m]` is the minimum ops to make `nums[i:]` to include all multiple of targets covered by `m`. # Approach To calculate `dp[i][m]` we use another mask `mm` who is a subset of `m`. From `dp[i+1][mm]` to `dp[i][m]` we need to make sure that the targets in `m` but not `mm` have multiple included post-op `nums[i]`. Namely, we need to increment `nums[i]` to the nearly multiple of the lcm of the targets in `m` but not in `mm`. Enumrating all valid `mm` results in `dp[i][m]`. Finally, `dp[0][(1<<t)-1]` gives the final answer. # Complexity - Time complexity: `O(N*2^T*2^T)` - Space complexity: `O(N*2^T)` # Code ```python3 [] class Solution: def minimumIncrements(self, nums: List[int], target: List[int]) -> int: n = len(nums) t = len(target) @cache def fn(i, m): """Return """ if i == n: return 0 if m == 0 else inf ans = fn(i+1, m) for mm in range(1<<t): if m & mm == mm: cand = 1 for j in range(t): if (m ^ mm) & 1<<j: cand = lcm(cand, target[j]) r = (cand - nums[i] % cand) % cand ans = min(ans, r + fn(i+1, mm)) return ans return fn(0, (1<<t)-1) ``` Bottom-up ```C++ [] class Solution { public: int minimumIncrements(vector<int>& nums, vector<int>& target) { int n = nums.size(), t = target.size(); vector<vector<long long>> dp(n+1, vector<long long>(1<<t, -1)); dp[n][0] = 0; for (int i = n-1; i >= 0; --i) for (int m = 0; m < 1<<t; ++m) { dp[i][m] = dp[i+1][m]; for (int mm = 0; mm < 1<<t; ++mm) if ((m & mm) == mm && dp[i+1][mm] != -1) { long long cand = 1; for (int j = 0; j < t; ++j) if ((m ^ mm) & 1<<j) cand = lcm(cand, target[j]); long long r = (cand - nums[i] % cand) % cand; if (dp[i][m] == -1) dp[i][m] = r + dp[i+1][mm]; else dp[i][m] = min(dp[i][m], r + dp[i+1][mm]); } } return dp[0][(1<<t)-1]; } }; ``` ```Java [] class Solution { private long gcd(long x, long y) { while (y > 0) { long t = x; x = y; y = t % y; } return x; } public int minimumIncrements(int[] nums, int[] target) { int n = nums.length, t = target.length; long[][] dp = new long[n+1][1<<t]; Arrays.fill(dp[n], -1); dp[n][0] = 0; for (int i = n-1; i >= 0; --i) for (int m = 0; m < 1<<t; ++m) { dp[i][m] = dp[i+1][m]; for (int mm = 0; mm < 1<<t; ++mm) if ((m & mm) == mm && dp[i+1][mm] != -1) { long cand = 1; for (int j = 0; j < t; ++j) if (((m ^ mm) & 1<<j) > 0) cand = cand * target[j] / gcd(cand, (long) target[j]); long r = (cand - nums[i] % cand) % cand; if (dp[i][m] == -1) dp[i][m] = r + dp[i+1][mm]; else dp[i][m] = Math.min(dp[i][m], r + dp[i+1][mm]); } } return (int) dp[0][(1<<t)-1]; } } ``` ```Python3 [] class Solution: def minimumIncrements(self, nums: List[int], target: List[int]) -> int: n = len(nums) t = len(target) dp = [[inf]*(1<<t) for _ in range(n+1)] dp[n][0] = 0 for i in range(n-1, -1, -1): for m in range(1<<t): dp[i][m] = dp[i+1][m] for mm in range(1<<t): if m & mm == mm: cand = 1 for j in range(t): if (m ^ mm) & 1<<j: cand = lcm(cand, target[j]) r = (cand - nums[i] % cand) % cand dp[i][m] = min(dp[i][m], r + dp[i+1][mm]) return dp[0][(1<<t)-1] ``` ```JavaScript [] var minimumIncrements = function(nums, target) { const n = nums.length, t = target.length; const dp = Array(n+1).fill(0).map(() => Array(1<<t).fill(Infinity)); dp[n][0] = 0; for (let i = n-1; i >= 0; --i) for (let m = 0; m < 1<<t; ++m) { dp[i][m] = dp[i+1][m]; for (let mm = 0; mm < 1<<t; ++mm) if ((m & mm) == mm) { let cand = 1; for (let j = 0; j < t; ++j) { let g = cand, t = target[j]; while (t) [g, t] = [t, g % t]; if ((m^mm) & 1<<j) cand = cand * target[j] / g; } const r = (cand - nums[i] % cand) % cand; dp[i][m] = Math.min(dp[i][m], r + dp[i+1][mm]); } } return dp[0][(1<<t)-1]; }; ```
7
1
['Python3']
1
minimum-increments-for-target-multiples-in-an-array
DP with BitMasking || O(16*16*n) || Must check || LCM of set bits indexed element
dp-with-bitmasking-o1616n-must-check-sim-im1e
Complexity Time complexity: O(16∗16∗n) Space complexity: O(n)Code
Priyanshu_pandey15
NORMAL
2025-02-02T04:02:37.622793+00:00
2025-02-03T07:15:26.775310+00:00
944
false
# Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> $$O(16*16*n)$$ - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> $$O(n)$$ # Code ```java [] class Solution { static public int minimumIncrements(int[] nums, int[] target) { Long[][] dp = new Long[nums.length + 1][(1 << target.length)]; long ans = solve(0, nums, target, 0, dp); return (int) ans; } static long solve(int i, int[] arr, int[] target, int mask, Long[][] dp) { int want = (1 << target.length) - 1; if (dp[i][mask] != null) { return dp[i][mask]; } if (i == arr.length) { if (mask == want) return 0; return 100000; } int current = want & ~mask; long ans = 100000, min = 100000; for (int j = current; j > 0; j = ((j - 1) & current)) { long lcm = LCM(j, target); long x = (long) (Math.ceil(arr[i] / (lcm * 1.0))); ans = ((lcm * x) - arr[i]) + solve(i + 1, arr, target, mask | j, dp); min = Math.min(min, ans); } long notConsider = solve(i + 1, arr, target, mask, dp); long result = Math.min(min, notConsider); dp[i][mask] = result; return result; } static long LCM(int mask, int[] target) { ArrayList<Long> l = new ArrayList<>(); for (int i = 0; i < target.length; i++) { if ((mask & (1 << i)) != 0) { l.add((long) target[i]); } } if (l.size() == 1) return l.get(0); long lcm = l.get(0); for (int i = 1; i < l.size(); i++) { lcm = (lcm * l.get(i)) / gcd(lcm, l.get(i)); } return lcm; } static long gcd(long a, long b) { if (a == 0) return b; return gcd(b % a, a); } } ```
6
1
['Dynamic Programming', 'Bit Manipulation', 'Java']
3
minimum-increments-for-target-multiples-in-an-array
Simple & Easy to understand Solution | Dynamic Programming
simple-easy-to-understand-solution-dynam-yfq2
IntuitionSince (1<=m<=4) && (1<=n<=1e9) so a clear intution of bit manipulation was there. Why dp? We can see that after some dry runs it's never sure whether b
Ayu1_2
NORMAL
2025-02-04T10:27:43.163949+00:00
2025-02-04T10:27:43.163949+00:00
257
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Since (1<=m<=4) && (1<=n<=1e9) so a clear intution of bit manipulation was there. Why dp? We can see that after some dry runs it's never sure whether by taking curr element ans will be optimal or not. So, it's a hint towards dp. # Approach <!-- Describe your approach to solving the problem. --> I solved the problem using 2D dp, where idx represents index of nums and mark will represent mask for target. ``` int temp = mark; for(int i=0;i<m;i++){ if(nums[idx]%tar[i] == 0) temp|= (1<<i); } int nottake = rec(nums, tar, dp, n, m, temp, idx+1); ``` here we skipped idx value to consider for updation and just mark all those values in tar which are factors of nums[idx]. ``` for(int i=0;i<m;i++){ if(mark & (1<<i)) continue; temp = mark; int op = tar[i] - nums[idx]%tar[i]; nums[idx]+= op; temp |= (1<<i); for(int j=0;j<m;j++){ if(temp & (1<<j)) continue; if(nums[idx]%tar[j] == 0) temp|= (1<<j); } nums[idx]-= op; take = min(take, op + rec(nums, tar, dp, n, m, temp, idx+1)); } ``` here for tarj we update the current nums[idx] value and mark all the others tar values which are also covered itself. And then we moved to idx+1. # Complexity - Time complexity: O(n * m * 2^m) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(n * 2^m) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { int rec(auto& nums, auto& tar, auto& dp, int n, int m, int mark, int idx){ if(idx == n){ if((1<<m) == mark+1) return 0; else return 1e9; } if(dp[idx][mark] != -1) return dp[idx][mark]; int take = 1e9; int temp = mark; for(int i=0;i<m;i++){ if(nums[idx]%tar[i] == 0) temp|= (1<<i); } int nottake = rec(nums, tar, dp, n, m, temp, idx+1); for(int i=0;i<m;i++){ if(mark & (1<<i)) continue; temp = mark; int op = tar[i] - nums[idx]%tar[i]; nums[idx]+= op; temp |= (1<<i); for(int j=0;j<m;j++){ if(temp & (1<<j)) continue; if(nums[idx]%tar[j] == 0) temp|= (1<<j); } nums[idx]-= op; take = min(take, op + rec(nums, tar, dp, n, m, temp, idx+1)); } return dp[idx][mark] = min(take, nottake); } public: int minimumIncrements(vector<int>& nums, vector<int>& target) { vector<vector<int>> dp(nums.size(), vector<int>(16, -1)); return rec(nums, target, dp, nums.size(), target.size(), 0, 0); } }; ```
5
0
['Array', 'Math', 'Dynamic Programming', 'Greedy', 'Bit Manipulation', 'Number Theory', 'Bitmask', 'C++']
0
minimum-increments-for-target-multiples-in-an-array
Scuffed solution
scuffed-solution-by-chitraksh24-a9ev
Code
chitraksh24
NORMAL
2025-02-02T04:03:09.661438+00:00
2025-02-02T04:03:09.661438+00:00
189
false
# Code ```python3 [] from itertools import permutations class Solution: def minimumIncrements(self, nums: List[int], target: List[int]) -> int: target = list(set(target)) answer = float("inf") nums.sort(reverse=True) concretenumslist = list(nums) for targs in permutations(target): nums = list(concretenumslist) ans = 0 used = set() for t in targs: curr = float('inf') ind = -1 for i, num in enumerate(nums): if num == t or num%t==0: curr = 0 ind = i break if i in used: continue if num<=t: if t-num<curr: ind = i curr = min(curr, t-num) else: if t-num%t<curr: ind = i curr = min(curr, t-num%t) used.add(ind) if nums[ind]>t: nums[ind] += curr else: nums[ind] = t ans += curr answer = min(answer, ans) return answer ```
3
0
['Python3']
2
minimum-increments-for-target-multiples-in-an-array
Python | Recursion | Memoization
python-recursion-memoization-by-pranav74-uypg
Complexity Time complexity: O(2M∗M∗N) Space complexity: O(M∗2M) Code
pranav743
NORMAL
2025-02-06T18:33:42.673847+00:00
2025-02-11T06:58:19.409715+00:00
98
false
# Complexity - Time complexity: $$O(2^ M ∗M∗N )$$ - Space complexity: $$O(M∗2^ M )$$ # Code ```python3 [] class Solution: def minimumIncrements(self, nums: List[int], target: List[int]) -> int: lcm_map = defaultdict(int) index_map = {1: 0, 2: 1, 4: 2, 8: 3} target_len = len(target) for mask in range(1, 2**target_len): curr_lcm, bit_mask = 1, 0 bit = 1 while bit < 2**target_len: if bit & mask: curr_lcm = lcm(curr_lcm, target[index_map[bit]]) bit_mask |= bit bit <<= 1 lcm_map[bit_mask] = curr_lcm def cost(i, curr_lcm): if curr_lcm == 0: return inf if nums[i] == curr_lcm: return 0 if curr_lcm > nums[i]: return curr_lcm - nums[i] return (ceil(nums[i] / curr_lcm) * curr_lcm) - nums[i] @cache def dfs(i, mask): if mask == 2**target_len - 1: return 0 if i >= len(nums): return inf min_cost = dfs(i + 1, mask) for new_mask in range(mask, 2**target_len): if mask & new_mask != mask: continue updated_mask = mask ^ new_mask min_cost = min(min_cost, cost(i, lcm_map[updated_mask]) + dfs(i + 1, new_mask)) return min_cost return dfs(0, 0) ```
2
0
['Dynamic Programming', 'Recursion', 'Memoization', 'Bitmask', 'Python3']
0
minimum-increments-for-target-multiples-in-an-array
DP with Bitmasking | Easy Solution
dp-with-bitmasking-easy-solution-by-prav-5aoo
IntuitionApproachComplexity Time complexity: Space complexity: Code
praveen1208
NORMAL
2025-02-03T14:34:29.505713+00:00
2025-02-03T14:36:31.582663+00:00
101
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: vector<vector<int>> dp; int m; int fun(vector<int>& nums,int i,int mask, vector<int>& t){ if(mask==(1<<m)-1) return 0; if(i==nums.size()) return 10000001; if(dp[i][mask]!=-1) return dp[i][mask]; int ans=fun(nums,i+1,mask,t); for(int j=0;j<m;j++){ if(mask&(1<<j)) continue; int d=nums[i]; if(nums[i]%t[j]) // if nums[i] is not divisible d+=(t[j]-nums[i]%t[j]); // incrase to make divisible int newmask=mask; for(int k=0;k<m;k++){ if(d%t[k]==0) //if it is divisible by other element newmask= newmask|(1<<k); // update mask } ans=min(ans, d-nums[i] +fun(nums,i+1,newmask,t)); } return dp[i][mask]=ans; } int minimumIncrements(vector<int>& nums, vector<int>& t) { int n=nums.size(); m=t.size(); dp.resize(n+1,vector<int>((1<<m)+1,-1)); return fun(nums,0,0,t); } }; ```
2
0
['C++']
0
minimum-increments-for-target-multiples-in-an-array
Java DP
java-dp-by-realstar-48rg
IntuitionIf target length is 1, then just go through nums and find each value's cost, return the min one. If target legnth is 2, then need at least n * 3 dp val
realstar
NORMAL
2025-02-03T04:23:49.579169+00:00
2025-02-03T04:23:49.579169+00:00
120
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> If target length is 1, then just go through nums and find each value's cost, return the min one. If target legnth is 2, then need at least n * 3 dp value (or 3 value since we only need prev's value, not other historical ones): First one: save the cost to make the target[0]'s multiplier. Second one: save the cost to make the target[1]'s multiplier. Third one: save the cost to fit both. For first value in nums, the first value dp[01(binary)]: cost to make nums[0] to fit target[0] second value dp[10]: cost to make nums[0] to fit target[1] last value dp[11]: cost to make nums[0] to fit both target[0] and target[1] (fit lcm of target[0] and target[1]). For the other's values (index j) in nums: dp[01]: check the cost to make nums[j] to fit target[0], if it is lower then existing one, update it. dp[10]: check the cost to make nums[j] to fit target[1] dp[11]: There are 3 ways to make it: 1, make nums[j] to fit lcm, if the cost is lower then dp[11], use it. 2, make nums[j] to fit target[0] and plus the cost of last dp[10], since we use cost dp[10] to make target[1] working, then we plus the cost make nums[j] to fit target[0], then we are good for both target. 3, make nums[j] to fit target[1] and plus the cost of last dp[01] Go through the nums, find the last dp[11], that is the result. If the target length is 3, we need at least n * 7 dp values: dp[001]: the cost to make it fit target[0] dp[010]: the cost to make it fit target[1] dp[100]: the cost to make it fit target[2] dp[011]: the cost to make it fit target[0] and target[1] dp[101]: the cost to make it fit target[0] and target[2] dp[110]: the cost to make it fit target[1] and target[2] dp[111]: the cost to make it fit all 3 value. Use dp[111] as example: It can get from: 1, nothing from prev, cost to make nums[j] to lcm of all. 2, prev dp[001] + current cost to fit lcm of (target 1, 2) -- lcm[110] 3, prev dp[010] + current cost to fit lcm of (target 0, 2) -- lcm[101] 4, prev dp[100] + current cost to fit lcm of (target 0, 1) -- lcm[011] 4, prev dp[011] + current cost to fit target 2 -- lcm[100] 4, prev dp[101] + current cost to fit target 1 -- lcm[010] 4, prev dp[110] + current cost to fit target 0 -- lcm[001] If we also put lcm to binary, then it is exactly the ^ of dp index value. This can expand to target length = 4. For each dp[abcd], the abcd's ones can either from prev dp, or from current cost, just check all the combinations. Like 1101, can do last 1000 + current 0101. Or last 1100 + current 0001. Or last 1001 + current 0100, ... (I didn't list all), just make sure 1101' all ones in either last or current. # Approach <!-- Describe your approach to solving the problem. --> Target length = 1, we need len = 1 Target length = 2, we need len = 3. Target length = 3, we need len = 7. Target length = 4, we need len = 15. Just make len = pow(2, target length), and ignore the index 0. # Complexity - Time complexity: 16 * 16 * n <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: 16 * n <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int minimumIncrements(int[] nums, int[] target) { int n = nums.length; int len = 1 << target.length; long[][] result = new long[n][len]; //will be the dp values. Using long is avoid overflow, then final result won't exceed, but the middle calculation may cause problem if only int. long[] lcm = new long[len]; //Save the combination of the lcm for (int i = 0; i < target.length; i++) lcm[1 << i] = target[i]; for (int i = 1; i < len; i++) { if (lcm[i] > 0) { result[0][i] = need(nums[0], lcm[i]); continue; } lcm[i] = 1; int index = 1; while (index < i) { if ((index & i) != 0) lcm[i] = lcm(lcm[i], lcm[index]); index = index << 1; } result[0][i] = need(nums[0], lcm[i]); } // calc lcm and the dp[0] values, the cost for nums[0] to fit each lcm combination. for (int j = 1; j < n; j++) { long[] now = new long[len]; for (int i = 1; i < len; i++) now[i] = need(nums[j], lcm[i]); for (int i = 1; i < len; i++) { result[j][i] = Math.min(result[j - 1][i], now[i]); for (int k = 1; k < len; k++) { if ((i | k) != i) continue; // ignore the ones no need, like when we calc 101, only need 001 and 100, we don't need any x1x costs result[j][i] = Math.min(result[j][i], now[k] + result[j - 1][i ^ k]); } } } return (int)result[n - 1][len - 1]; } private static long need(long num, long target) { long mod = num % target; if (mod == 0) return 0; else return target - mod; } private static long gcd(long a, long b) { if (a == 0) return b; if (b == 0) return a; if (a == b) return a; if (a > b) return gcd(a % b, b); return gcd(a, b % a); } private static long lcm(long a, long b) { long gcd = gcd(a, b); return (a / gcd) * b; } } ```
2
0
['Java']
0
minimum-increments-for-target-multiples-in-an-array
EASY TO UNDERSTAND BITMASK DP in C++ with INTUITION and Explanation
easy-to-understand-bitmask-dp-in-c-with-q4olu
IntuitionWe have m+1(where m is size of target array) choices for each nums[i]: 1.Do not change nums[i] 2.Change nums[i] to nearest multiple of target[0]. 3.Cha
Kunal_Sobti
NORMAL
2025-02-07T13:10:23.684518+00:00
2025-02-07T13:10:23.684518+00:00
72
false
# Intuition We have m+1(where m is size of target array) choices for each nums[i]: 1.Do not change nums[i] 2.Change nums[i] to nearest multiple of target[0]. 3.Change nums[i] to nearest multiple of target[1]. ...and so on. Hence it is a DP problem. Now a single nums[i] can be a common multiple of more than one targets hence at each call we have to check after performing one of the above m+1 operations ,thatr my current nums[i] is multiple for which target[i]'s. Also in my Base Case my task is done only when all the targets have a multiple in nums. Since there is so much repeated task and every time we have to keep track of which target[i] have there multiples in nums,I will use a Bitmask DP(also because the target array constraint is 4 only) # Approach I will represent each of target[i] by a bit equivalent to their index in target array I will have a target Bit which will be equal to (2^m)-1 i.e all bits must be one which represents that all targets have atleast one multiple in nums. I will also have a curr variable in recursion which will keep track of which targets have been fullfilled uptill now. I will update curr by bitwise ORing it with the target bits that current nums[i] is a multiple of. Rest is Memiozation and simple DP. This is my first post ,please upvote if u like it and comment for any improvements or errors .This will give me motivation to post from now on. Thank You! # Complexity - Time complexity: O(N* M* (2^M)) nums size---N target size--M as in the dp array there will be n*targetBit which is N*(2^M) unique states and in each state I am also iterating the target array once of size M - Space complexity: DP array space only --O(n*2^m) # Code ```cpp [] class Solution { public: int f(int i,int curr,int targetBit,vector<int>&nums,vector<int>&target,vector<vector<int>>&dp){ if(curr==targetBit)return 0; if(i==nums.size())return 1e9; if(dp[i][curr]!=-1)return dp[i][curr]; int mini=1e9; // no change: int noChangeBit=0; for(int k=0;k<target.size();k++){ if(nums[i]%target[k]==0)noChangeBit|=(1<<k); } mini=min(mini,f(i+1,curr|noChangeBit,targetBit,nums,target,dp)); // change: for(int j=0;j<target.size();j++){ int op=(target[j]-(nums[i]%target[j])); int temp=nums[i]+op; int tempBit=0; for(int k=0;k<target.size();k++){ if(temp%target[k]==0)tempBit|=(1<<k); } mini=min(mini,op+f(i+1,curr|tempBit,targetBit,nums,target,dp)); } return dp[i][curr]=mini; } int minimumIncrements(vector<int>& nums, vector<int>& target) { int n=nums.size(); int m=target.size(); int targetBit=(1<<m)-1; vector<vector<int>>dp(n,vector<int>(targetBit,-1)); return f(0,0,targetBit,nums,target,dp); } }; ```
1
0
['Dynamic Programming', 'Bit Manipulation', 'Bitmask', 'C++']
1
minimum-increments-for-target-multiples-in-an-array
C++ | Beats 96% | Submask Enumeration | Bitmasking | O(n*m*3^m + 2^m) | Better Complexity
c-beats-96-submask-enumeration-bitmaskin-5f14
Complexity Time complexity: O(n∗m∗3m) Please read all-submasks for more details on how to arrive at this complexity. Code
lord-chicken
NORMAL
2025-02-05T11:49:02.173682+00:00
2025-02-05T13:56:04.275391+00:00
69
false
# Complexity - Time complexity: $$O(n*m*3^m)$$ > Please read [all-submasks](https://cp-algorithms.com/algebra/all-submasks.html) for more details on how to arrive at this complexity. # Code ```cpp [] class Solution { int M, m, n; vector<long long> mask_to_lcm; int solve(vector<int>& nums, vector<int>& target, int mask, int id, vector<vector<int>>& dp) { if (mask == 0) return 0; if (id == n) return INT_MAX; if (dp[mask][id] != -1) return dp[mask][id]; long long res = solve(nums, target, mask, id + 1, dp); for (int sub = mask ; sub ; sub = (sub - 1) & mask) { long long x = 0, lc = mask_to_lcm[sub]; x = nums[id] % lc; if (x) x = lc - x; res = min(res, x + solve(nums, target, mask ^ sub, id + 1, dp)); } return dp[mask][id] = res; } public: int minimumIncrements(vector<int>& nums, vector<int>& target) { n = nums.size(); m = target.size(); M = 1 << m; vector<vector<int>> dp(M, vector<int>(n, -1)); mask_to_lcm.resize(M); for (int mask = 1 ; mask < M ; ++mask) { mask_to_lcm[mask] = 1; for (int i = 0 ; i < m ; ++i) { if ((1 << i) & mask) { mask_to_lcm[mask] = lcm(mask_to_lcm[mask], (long long)target[i]); } } } return solve(nums, target, M - 1, 0, dp); } }; ```
1
0
['C++']
0