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
calculate-digit-sum-of-a-string
python3 simple solution
python3-simple-solution-by-mxmb-c2ds
python\ndef digitSum(self, s: str, k: int) -> str:\n while len(s) > k:\n arr = [s[i:i+k] for i in range(0,len(s),k)] # divide \n ar
mxmb
NORMAL
2022-04-23T18:02:35.890528+00:00
2022-04-23T18:03:17.623646+00:00
156
false
```python\ndef digitSum(self, s: str, k: int) -> str:\n while len(s) > k:\n arr = [s[i:i+k] for i in range(0,len(s),k)] # divide \n arr = [str(sum(int(i) for i in s)) for s in arr] # replace\n s = \'\'.join(arr) # merge\n return s\n```
1
0
['Python', 'Python3']
0
calculate-digit-sum-of-a-string
C++ | 0ms Solution | Recursion with comments
c-0ms-solution-recursion-with-comments-b-ewr2
\nclass Solution {\npublic:\n string digitSum(string s, int k) {\n // if length is smaller or equal to k, no more rounds left\n if (s.length()
rohit2706
NORMAL
2022-04-21T13:28:47.861191+00:00
2022-04-21T13:28:47.861234+00:00
38
false
```\nclass Solution {\npublic:\n string digitSum(string s, int k) {\n // if length is smaller or equal to k, no more rounds left\n if (s.length() <= k)\n return s;\n \n // find string after this round\n string round_str;\n for (int i=0; i<s.length(); i+=k) {\n int sum = 0;\n // process the next group of size <= k by summing individual digits\n for (int j=i; j<i+k && j<s.length(); j++){\n sum += s[j]-\'0\';\n }\n \n // append sum to final sring\n round_str += to_string(sum);\n }\n \n // recursion to proceed to next round\n return digitSum(round_str, k);\n }\n};\n```
1
0
[]
0
calculate-digit-sum-of-a-string
[Python] | Simple Simulation solution
python-simple-simulation-solution-by-gre-29di
This is my first post, so let\'s start with an easy one.\nWhat we want to do here is to simulate the rounds by iterating until our string s is shorter than k, a
gregalletti
NORMAL
2022-04-20T10:55:39.471003+00:00
2022-04-20T16:49:40.797272+00:00
118
false
*This is my first post, so let\'s start with an easy one.*\nWhat we want to do here is to **simulate the rounds** by iterating until our string `s` is shorter than `k`, and in the loop we:\n* split `s` in groups of length `k` and store the results in a list `groups`\n* calculate the sum of the digits of each group `g` and store the results in `s`\n* return `s` when we exit the loop\n```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n while len(s) > k:\n groups = [s[i:i+k] for i in range(0, len(s), k)]\n s = ""\n for g in groups:\n tot = sum(int(n) for n in g)\n s += str(tot)\n return s\n```\n\n**Runtime:** 24 ms\n**Beats:** 98.22%\n\nI hope it\'s helpful! And if you have some advices please let me know, I have a lot to learn \u270C\uFE0F
1
0
['Python', 'Python3']
0
calculate-digit-sum-of-a-string
Easy C++ Solution
easy-c-solution-by-shreya_2506-aaxx
class Solution {\npublic:\n string digitSum(string s, int k) {\n \n while(s.size()>k){\n \n int a=0,cnt=0;\n s
Shreya_2506
NORMAL
2022-04-20T06:32:15.375269+00:00
2022-04-20T06:32:15.375300+00:00
83
false
class Solution {\npublic:\n string digitSum(string s, int k) {\n \n while(s.size()>k){\n \n int a=0,cnt=0;\n string t="";\n \n for(int i=0;i<s.size();i++){\n \n a+=(s[i]-\'0\');\n cnt++;\n if(cnt==k){\n t+=to_string(a);\n cnt=0;\n a=0;\n }\n }\n if(cnt>0)\n t+=to_string(a);\n \n s=t;\n }\n return s;\n }\n};
1
0
['String', 'C']
0
calculate-digit-sum-of-a-string
a few solutions
a-few-solutions-by-claytonjwong-l5lk
Recursively reduce the input string s into k-sized chunks.\n\n---\n\nKotlin\n\nclass Solution {\n fun digitSum(s: String, k: Int): String {\n var N =
claytonjwong
NORMAL
2022-04-19T15:45:21.174902+00:00
2022-04-19T15:48:03.044563+00:00
47
false
Recursively reduce the input string `s` into `k`-sized chunks.\n\n---\n\n*Kotlin*\n```\nclass Solution {\n fun digitSum(s: String, k: Int): String {\n var N = s.length\n if (N <= k)\n return s\n var f = { s: String -> s.toCharArray().map{ it.toInt() - \'0\'.toInt() }.sum()!! }\n return digitSum(s.chunked(k).map{ f(it) }.joinToString(""), k)\n }\n}\n```\n\n*Javascript*\n```\nlet digitSum = (s, k) => {\n let N = s.length;\n if (N <= k)\n return s;\n let A = [];\n for (let i = 2; i <= N; ++i)\n if (!(i % k))\n A.push(s.substr(i - k, k));\n let mod = N % k;\n if (mod)\n A.push(s.substr(N - mod, mod));\n let f = s => _.sum(s.split(\'\').map(c => c.charCodeAt(0) - \'0\'.charCodeAt(0)));\n return digitSum(A.map(s => f(s)).join(\'\'), k);\n};\n```\n\n*Python3*\n```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n N = len(s)\n if N <= k:\n return s\n A = [s[i:i + k] for i in range(0, N, k)]\n f = lambda s: sum(int(c) for c in s)\n return self.digitSum(\'\'.join([str(f(s)) for s in A]), k)\n```\n\n*Rust: this solution is based upon [BigMih\'s solution](https://leetcode.com/problems/calculate-digit-sum-of-a-string/discuss/1957505/Rust-solution)*\n```\nimpl Solution {\n pub fn digit_sum(s: String, k: i32) -> String {\n let k = k as usize;\n let mut s = s;\n while !(s.len() <= k) {\n s = s.chars().collect::<Vec<_>>().chunks(k)\n .map(|it| it.iter().map(|c| c.to_digit(10).unwrap()).sum::<u32>().to_string())\n .collect::<Vec<_>>().join("");\n }\n return s;\n }\n}\n```\n\n*C++*\n```\nclass Solution {\npublic:\n using VS = vector<string>;\n string digitSum(string s, int k, VS A = {}) {\n int N = s.size();\n if (N <= k)\n return s;\n for (auto i{ 2 }; i <= N; ++i)\n if (!(i % k))\n A.push_back(s.substr(i - k, k));\n int mod = N % k;\n if (mod)\n A.push_back(s.substr(N - mod, mod));\n auto f = [](auto& s) {\n return accumulate(s.begin(), s.end(), 0, [](auto t, auto c) {\n return t + c - \'0\';\n });\n };\n ostringstream os;\n for (auto& s: A)\n os << f(s);\n return digitSum(os.str(), k);\n }\n};\n```
1
0
[]
0
calculate-digit-sum-of-a-string
Python || Easy Solution
python-easy-solution-by-nashvenn-7ix9
Please upvote if it helps. Thank you!\n\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n while len(s) > k:\n new_s = \'\'\n
nashvenn
NORMAL
2022-04-18T20:26:48.458671+00:00
2022-04-18T20:26:48.458712+00:00
66
false
**Please upvote if it helps. Thank you!**\n```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n while len(s) > k:\n new_s = \'\'\n for i in range(0, len(s), k):\n new_s += str(sum([int(c) for c in s[i:i+k]]))\n s = new_s[:]\n return s\n```
1
0
['Python']
0
calculate-digit-sum-of-a-string
Python beats 100% memory 85% space | With Comments
python-beats-100-memory-85-space-with-co-3z5u
\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n \n # Requirement 3; Merge groups when string s > k\n while len(s) > k:\
krazynukz
NORMAL
2022-04-17T18:41:51.443134+00:00
2022-04-17T18:41:51.443182+00:00
88
false
```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n \n # Requirement 3; Merge groups when string s > k\n while len(s) > k:\n temp = "" # Will contain the next round\'s string s\n i = 0 # counter to exit while loop below, when out of groups\n \n # Requirement 1; divide string s into groups of size k\n while i < len(s): \n groupVal = 0 # Will contain sum of current group\'s digits\n \n # Requirement 3; Merge group into sum of all digits\n for c in s[i:i+k]: # Take each character of the current group and add to sum of digits\n groupVal += int(c) \n temp += str(groupVal) # cast sum to string and append to next round\'s string s\n i += k\n s = temp \n return s\n```\nHope this makes sense! Feel free to provide suggestions
1
0
['String', 'Python']
1
calculate-digit-sum-of-a-string
Short Python while loop
short-python-while-loop-by-hszh-kkgu
\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n \n while len(s) > k:\n curr = []\n for i in range(0, len
hsZh
NORMAL
2022-04-17T15:01:20.731836+00:00
2022-04-17T15:04:06.190380+00:00
40
false
```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n \n while len(s) > k:\n curr = []\n for i in range(0, len(s), k):\n curr.append(str(sum(int(s[j]) for j in range(i, min(len(s),i+k)))))\n s = \'\'.join(curr)\n \n return s\n```\n\n\nslightly update version :\n\n```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n \n while len(s) > k:\n curr = \'\'\n for i in range(0, len(s), k):\n curr+=str(sum(int(s[j]) for j in range(i, min(len(s),i+k))))\n s = curr\n \n return s\n```
1
0
['Python']
0
calculate-digit-sum-of-a-string
✅ C++ | Easy to understand
c-easy-to-understand-by-rupam66-2pfu
\nclass Solution {\npublic:\n string digitSum(string s, int k) {\n if(s.size()<=1) return s;\n while(s.size()>k){\n string tmp;\n
rupam66
NORMAL
2022-04-17T14:09:55.296264+00:00
2022-04-17T14:09:55.296304+00:00
56
false
```\nclass Solution {\npublic:\n string digitSum(string s, int k) {\n if(s.size()<=1) return s;\n while(s.size()>k){\n string tmp;\n int num=0;\n for(int i=0;i<s.size();i++){\n if(i && i%k==0){\n tmp+=to_string(num);\n num=0;\n }\n num+=s[i]-\'0\';\n }\n tmp+=to_string(num);\n s=tmp;\n }\n return s;\n }\n};\n```
1
0
['String', 'C']
0
calculate-digit-sum-of-a-string
5-Lines Python Solution || 100% Faster || Memory less than 85%
5-lines-python-solution-100-faster-memor-bwr7
\n\n\n### Solution: TC O((n/k)\n) / SC O(n)\n\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n while len(s)>k:\n tmp=\'\'\n
Taha-C
NORMAL
2022-04-17T14:06:40.417026+00:00
2022-04-17T14:41:10.528848+00:00
88
false
![image](https://assets.leetcode.com/users/images/7116de29-f9e8-4941-a72f-528d52cbef18_1650204904.767027.png)\n\n\n### ***Solution: TC O((n/k)\\*n) / SC O(n)***\n```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n while len(s)>k:\n tmp=\'\'\n for i in range(0,len(s),k): tmp+=str(sum([int(d) for d in s[i:i+k]]))\n s=tmp\n return s\n```\n\n-----------------\n### ***One-Line Version:***\n```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n return self.digitSum(\'\'.join(str(sum(int(d) for d in s[i:i+k])) for i in range(0,len(s),k)), k) if len(s) > k else s\n```\n-------------------\n***----- Taha Choura -----***\n*[email protected]*\n
1
0
['Python', 'Python3']
0
calculate-digit-sum-of-a-string
Simple Python Solution
simple-python-solution-by-lcshiung-ix9k
\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n \n final_s = s\n while len(final_s) > k:\n new_s = \'\'
lcshiung
NORMAL
2022-04-17T13:37:39.820906+00:00
2022-04-17T17:19:15.599422+00:00
25
false
```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n \n final_s = s\n while len(final_s) > k:\n new_s = \'\' # newly formed string\n k_length_sub_s = \'\' # k-length substring\n for i in range(len(final_s)):\n k_length_sub_s += final_s[i]\n if (i+1) % k == 0 or i+1 == len(final_s): # if we have formed k-length substring, or if last letter\n sum_s = sum([int(x) for x in k_length_sub_s]) # calculate sum of k-length substring\n new_s += str(sum_s) # append k-length substring to newly formed string\n k_length_sub_s = \'\'\n final_s = new_s # update newly formed string\n \n return final_s\n```
1
0
[]
0
calculate-digit-sum-of-a-string
Java
java-by-ryann10-o1an
\nclass Solution {\n public String digitSum(String s, int k) {\n while (s.length() > k) {\n int groups = s.length() / k + (s.length() % k =
ryann10
NORMAL
2022-04-17T12:59:34.302437+00:00
2022-04-17T12:59:34.302465+00:00
70
false
```\nclass Solution {\n public String digitSum(String s, int k) {\n while (s.length() > k) {\n int groups = s.length() / k + (s.length() % k == 0 ? 0 : 1);\n \n StringBuilder sb = new StringBuilder();\n \n for (int i = 0; i < groups; i++) {\n int sum = 0;\n \n int size = i == groups - 1 ? s.length() - i * k : k;\n \n for (int j = 0; j < size; j++) {\n sum += s.charAt(i * k + j) - \'0\'; \n }\n \n sb.append(sum);\n }\n \n s = sb.toString();\n }\n \n return s;\n }\n}\n```
1
0
['String', 'Java']
0
calculate-digit-sum-of-a-string
Python | Recursive Solution | Easy to understand
python-recursive-solution-easy-to-unders-vozq
```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n def util(s):\n\t\t\t# if length of s is less than or equal to k, then we can not m
parmardiwakar150
NORMAL
2022-04-17T12:23:45.641159+00:00
2022-04-17T12:25:57.604575+00:00
36
false
```\nclass Solution:\n def digitSum(self, s: str, k: int) -> str:\n def util(s):\n\t\t\t# if length of s is less than or equal to k, then we can not make s any shorter\n if len(s) <= k:\n return s\n ans = \'\'\n for i in range(0, len(s), k):\n ans += str(sum(int(c) for c in s[i:i + k]))\n\t\t\t# If new string\'s length is more than k, call the function recursively\n if len(ans) > k:\n return util(ans)\n return ans\n return util(s)
1
0
['Recursion']
0
calculate-digit-sum-of-a-string
Simple Recursive Java Solution with comments
simple-recursive-java-solution-with-comm-4z8l
\nclass Solution {\n public String digitSum(String s, int k) {\n if (s.length() <= k) return s;\n \n StringBuilder sb = new StringBuilde
pure_aloha
NORMAL
2022-04-17T10:51:46.913716+00:00
2022-04-17T10:51:46.913756+00:00
45
false
```\nclass Solution {\n public String digitSum(String s, int k) {\n if (s.length() <= k) return s;\n \n StringBuilder sb = new StringBuilder();\n for (int i=0; i < s.length(); i += k) {\n int start = i;\n int end = Math.min(i + k, s.length()); // To avoid indexOutOfBoundsException\n int sum = findDigitSum(s.substring(start, end));\n sb.append(sum);\n }\n \n return digitSum(sb.toString(), k);\n }\n \n \n // Method to calculate the sum of digits of the string\n private int findDigitSum(String s) {\n int sum = 0;\n int i = 0;\n while (i < s.length()) {\n sum += (s.charAt(i) - \'0\');\n i++;\n }\n \n return sum;\n }\n}\n```
1
0
['Recursion', 'Java']
1
find-maximum-number-of-string-pairs
Explained using map || Very simple & easy to understand solution
explained-using-map-very-simple-easy-to-j0ekd
Upvote if you like the solution\n# Approach\n1. Take a map with seen string as the index and its count as its value.\n2. Iterate the words vector and check if i
kreakEmp
NORMAL
2023-06-24T16:07:27.638358+00:00
2023-06-24T19:14:19.951377+00:00
4,159
false
#### Upvote if you like the solution\n# Approach\n1. Take a map with seen string as the index and its count as its value.\n2. Iterate the words vector and check if its reverse exist in the map or not. \n3. If exist in the map then update the ans and decrement the map value as the we have considered this value for pairing.\n\n# Code\n```\n int maximumNumberOfStringPairs(vector<string>& words) {\n int ans = 0;\n unordered_map<string, int> mp;\n for(auto w: words){\n string r = w;\n reverse(r.begin(), r.end());\n if(mp[r] > 0){ ans++; mp[r]--; }\n else mp[w]++;\n }\n return ans;\n }\n```\n\n<b> Here is an article of my last interview experience - A Journey to FAANG Company, I recomand you to go through this to know which all resources I have used & how I cracked interview at Amazon:\nhttps://leetcode.com/discuss/interview-experience/3171859/Journey-to-a-FAANG-Company-Amazon-or-SDE2-(L5)-or-Bangalore-or-Oct-2022-Accepted
25
1
['C++']
4
find-maximum-number-of-string-pairs
676
676-by-votrubac-8zsx
There are 676 possible 2-character strings.\n\nSo, we use a boolean array to track if we\'ve seen a string before.\n\n> Note that we track reversed strings in t
votrubac
NORMAL
2023-06-24T16:20:11.653861+00:00
2024-06-18T21:41:57.687449+00:00
1,483
false
There are 676 possible 2-character strings.\n\nSo, we use a boolean array to track if we\'ve seen a string before.\n\n> Note that we track reversed strings in the boolean array. \n\n**C++**\n```cpp\nint maximumNumberOfStringPairs(vector<string>& words) {\n int vis[676] = {}, res = 0;\n for (const auto &w : words) {\n res += vis[(w[1] - \'a\') * 26 + w[0] - \'a\'];\n vis[(w[0] - \'a\') * 26 + w[1] - \'a\'] = true;\n }\n return res;\n}\n```
23
1
['C']
7
find-maximum-number-of-string-pairs
✅[Python] Simple and Clean, beats 88%✅
python-simple-and-clean-beats-88-by-_tan-14nq
Please upvote if you find this helpful. \u270C\n\n\n\n# Intuition\nThe problem asks us to find the maximum number of pairs that can be formed from a given list
_Tanmay
NORMAL
2023-07-05T09:54:04.927628+00:00
2023-07-05T09:54:04.927659+00:00
1,175
false
### Please upvote if you find this helpful. \u270C\n<img src="https://assets.leetcode.com/users/images/b8e25620-d320-420a-ae09-94c7453bd033_1678818986.7001078.jpeg" alt="Cute Robot - Stable diffusion" width="200"/>\n\n\n# Intuition\nThe problem asks us to find the maximum number of pairs that can be formed from a given list of words, where two words can be paired if one is the reverse of the other. We can use a set to keep track of the reversed versions of the words we have seen so far, and increment our answer whenever we encounter a word that is already in the set.\n\n# Approach\n1. Initialize an empty set `strings` to keep track of the reversed versions of the words we have seen so far.\n2. Initialize a variable `ans` to 0 to keep track of the number of pairs we have found.\n3. Iterate over each word `w` in `words`.\n4. If `w` is in `strings`, increment `ans` by 1.\n5. Otherwise, add the reversed version of `w` to `strings`.\n6. Return `ans`.\n\n# Complexity\n- Time complexity: $$O(nk)$$, where $$n$$ is the number of words and $$k$$ is the maximum length of a word.\n- Space complexity: $$O(nk)$$, where $$n$$ is the number of words and $$k$$ is the maximum length of a word.\n\n\n# Code\n```\nclass Solution:\n def maximumNumberOfStringPairs(self, words: List[str]) -> int:\n strings = set()\n ans = 0\n for w in words:\n if w in strings:\n ans += 1\n else:\n strings.add(w[::-1])\n return ans\n```
15
0
['Array', 'Hash Table', 'String', 'Ordered Set', 'Python3']
5
find-maximum-number-of-string-pairs
[C++/JAVA/PYTHON] O(1) Space || Easy to Understand || With Explanation
cjavapython-o1-space-easy-to-understand-khcrl
Time complexity : O(n^2)\n- Space complexity : O(1)\n# C++ Code\n\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(vector<string>& v) {\n i
Aditya00
NORMAL
2023-06-24T16:15:24.571875+00:00
2023-06-24T18:22:04.297415+00:00
2,217
false
- Time complexity : O(n^2)\n- Space complexity : O(1)\n# C++ Code\n```\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(vector<string>& v) {\n int ans = 0; // Initialize the variable to store the answer\n int n = v.size(); \n\n // Iterate over all pairs of strings\n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n\n // Check if i-th string is eaqual to reverse of j-th string\n if (v[i][0] == v[j][1] && v[i][1] == v[j][0]) {\n ans++; // Increment the count of matching pairs\n }\n }\n }\n\n return ans; // Return the total number of matching pairs\n }\n};\n\n```\n# Phython Code\n```\nclass Solution:\n def maximumNumberOfStringPairs(self, word: List[str]) -> int:\n ans = 0\n n = len(word)\n for i in range(n):\n for j in range(i+1, n):\n if word[i][0] == word[j][1] and word[i][1] == word[j][0]:\n ans += 1\n return ans\n```\n# JAVA Code \n```\nclass Solution {\n public int maximumNumberOfStringPairs(String[] words) {\n int ans = 0;\n int n = words.length;\n for (int i = 0; i < n; i++) {\n for (int j = i + 1; j < n; j++) {\n if (words[i].charAt(0) == words[j].charAt(1) && words[i].charAt(1) == words[j].charAt(0)) {\n ans++;\n }\n }\n }\n return ans;\n }\n}\n```
15
1
['C++']
2
find-maximum-number-of-string-pairs
Python 3 || 3 lines, w/ explanation || T/S: 99% / 96% .
python-3-3-lines-w-explanation-ts-99-96-huga6
Here\'s how the code works:\n\nThe code initializesdto keep track of the count of each word or its reverse.\n\nWe iterate over each word inwords, and we use the
Spaulding_
NORMAL
2023-07-29T16:57:46.041055+00:00
2024-06-23T15:34:20.724193+00:00
1,035
false
Here\'s how the code works:\n\nThe code initializes`d`to keep track of the count of each word or its reverse.\n\nWe iterate over each word in`words`, and we use the lexicographic minimum of the word and its reverse (`word[::-1]`)as the key for loading `words` into `d`, which ensures that the same pair is counted only once.\n\nWe return the sum of the counts of pairs in each value (using`x*(x-1)//2`) as the answer.\n```\nclass Solution:\n def maximumNumberOfStringPairs(self, words: List[str]) -> int:\n\n d = defaultdict(int)\n\n for word in words:\n d[min(word, word[::-1])]+= 1\n \n return sum(map((lambda x: x*(x-1)), d.values()))//2\n```\n[https://leetcode.com/problems/find-maximum-number-of-string-pairs/submissions/1292813544/](https://leetcode.com/problems/find-maximum-number-of-string-pairs/submissions/1292813544/)\n\n\nI could be wrong, but I think that time complexity is *O*(*NM*) and space complexity is *O*(*N*), in which *N* ~`len(nums)` and *M* ~ average`len(word)`.\n
9
0
['Python3']
0
find-maximum-number-of-string-pairs
Easy c++ solution using unordered set
easy-c-solution-using-unordered-set-by-r-z0v4
Intuition\n Describe your first thoughts on how to solve this problem. \nreverse and check the string is present in the set\n\n# Approach\n Describe your appr
rajgaurav95
NORMAL
2023-06-24T16:08:01.238133+00:00
2023-06-24T16:15:52.073323+00:00
1,862
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nreverse and check the string is present in the set\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)$$ -->\nO(n)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n\n# Code\n```\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(vector<string>& words) {\n unordered_set<string>mp;\n int res=0;\n for(auto it:words){\n string s=it;\n reverse(it.begin(),it.end());\n if(mp.find(it)==mp.end()){\n mp.insert(s);\n }\n else res++;\n \n }\n return res;\n }\n};\n```
9
0
['C++']
2
find-maximum-number-of-string-pairs
🧩 [VIDEO] Maximum Number of String Pairs 🔀 - Reversed String Pairing
video-maximum-number-of-string-pairs-rev-qwzf
Intuition\nUpon reading the problem, it\'s apparent that we need to pair strings that are the reverse of each other. The first instinct is to use a data structu
vanAmsen
NORMAL
2023-07-25T21:50:53.116825+00:00
2023-07-25T22:06:57.504868+00:00
844
false
# Intuition\nUpon reading the problem, it\'s apparent that we need to pair strings that are the reverse of each other. The first instinct is to use a data structure that allows quick lookups to check for the existence of a reversed word. A Python dictionary fits this need perfectly.\n\nhttps://www.youtube.com/watch?v=zL2d3G-nO0A\n\n# Approach\nWe\'ll start by initializing an empty dictionary and a counter variable to track the number of pairs. Next, we iterate through each word in the list. For each word, we generate its reversed counterpart and check if this reversed word is in the dictionary. If it is, we increment our counter and remove the reversed word from the dictionary, effectively forming a pair. If not, we add the original word to the dictionary. This process continues until we\'ve iterated through all the words. Finally, we return the counter as the result, which is the maximum number of pairs we can form.\n\n# Complexity\n- Time complexity: The time complexity is \\(O(n)\\) where \\(n\\) is the length of the input list. This is because we\'re iterating through the list once.\n\n- Space complexity: The space complexity is also \\(O(n)\\) in the worst-case scenario where no words can be paired and all words end up in the dictionary.\n\nIn the code, we\'ve used Python\'s string slicing feature to reverse the string and dictionary\'s quick lookup feature to find the reversed string. This solution thus efficiently solves the problem.\n\n# Code\n``` Python []\nclass Solution:\n def maximumNumberOfStringPairs(self, words: List[str]) -> int:\n word_dict = {} \n pairs = 0 \n for word in words: \n reversed_word = word[::-1] \n if reversed_word in word_dict: \n word_dict.pop(reversed_word) \n pairs += 1 \n else: \n word_dict[word] = 1 \n return pairs \n```\n``` C++ []\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(vector<string>& words) {\n std::unordered_map<std::string, int> word_dict;\n int pairs = 0;\n for (auto& word : words) {\n std::string reversed_word = word;\n std::reverse(reversed_word.begin(), reversed_word.end());\n if (word_dict[reversed_word]) {\n word_dict[reversed_word]--;\n pairs++;\n }\n else {\n word_dict[word]++;\n }\n }\n return pairs;\n }\n};\n```\n``` Java []\nclass Solution {\n public int maximumNumberOfStringPairs(String[] words) {\n HashMap<String, Integer> word_dict = new HashMap<>();\n int pairs = 0;\n for (String word : words) {\n String reversed_word = new StringBuilder(word).reverse().toString();\n if (word_dict.containsKey(reversed_word) && word_dict.get(reversed_word) > 0) {\n word_dict.put(reversed_word, word_dict.get(reversed_word) - 1);\n pairs++;\n }\n else {\n word_dict.put(word, word_dict.getOrDefault(word, 0) + 1);\n }\n }\n return pairs; \n }\n}\n```\n``` JavaScript []\n/**\n * @param {string[]} words\n * @return {number}\n */\nvar maximumNumberOfStringPairs = function(words) {\n let word_dict = {};\n let pairs = 0;\n for (let word of words) {\n let reversed_word = word.split(\'\').reverse().join(\'\');\n if (word_dict[reversed_word]) {\n word_dict[reversed_word]--;\n pairs++;\n }\n else {\n word_dict[word] = (word_dict[word] || 0) + 1;\n }\n }\n return pairs; \n};\n```\n``` C# []\npublic class Solution {\n public int MaximumNumberOfStringPairs(string[] words) {\n Dictionary<string, int> word_dict = new Dictionary<string, int>();\n int pairs = 0;\n foreach (string word in words) {\n char[] arr = word.ToCharArray();\n Array.Reverse(arr);\n string reversed_word = new string(arr);\n if (word_dict.ContainsKey(reversed_word) && word_dict[reversed_word] > 0) {\n word_dict[reversed_word]--;\n pairs++;\n }\n else {\n if (!word_dict.ContainsKey(word)) word_dict[word] = 0;\n word_dict[word]++;\n }\n }\n return pairs; \n }\n}\n```
8
0
['C++', 'Java', 'Python3', 'JavaScript', 'C#']
1
find-maximum-number-of-string-pairs
How to be in top by time complexity
how-to-be-in-top-by-time-complexity-by-n-hej5
Code\n\nclass Solution:\n def maximumNumberOfStringPairs(self, words: List[str]) -> int:\n total = 0\n c = set()\n for i in range(len(wo
NurzhanSultanov
NORMAL
2024-02-12T12:04:54.864126+00:00
2024-02-12T12:04:54.864168+00:00
415
false
# Code\n```\nclass Solution:\n def maximumNumberOfStringPairs(self, words: List[str]) -> int:\n total = 0\n c = set()\n for i in range(len(words)):\n for j in range(i + 1, len(words)):\n word1 = words[i]\n word2 = words[j]\n\n if word1 == word2[::-1] and word1 not in c and word2 not in c:\n total += 1\n c.add(word1)\n c.add(word2)\n return total\n```
6
0
['Python3']
1
find-maximum-number-of-string-pairs
✅Runtime 12 ms Beats 🚀100% and 💡Memory 13 MB Beats 📉99.67%
runtime-12-ms-beats-100-and-memory-13-mb-vtjt
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
deleted_user
NORMAL
2023-10-19T16:33:27.068540+00:00
2023-10-19T16:33:27.068570+00:00
263
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# Runtime 12 ms Beats \uD83D\uDE80100% \n```\nclass Solution(object):\n def maximumNumberOfStringPairs(self, words):\n pairs = 0\n reverse_dict = {}\n\n for word in words:\n reverse_word = word[::-1]\n if reverse_word in reverse_dict:\n pairs += reverse_dict[reverse_word]\n reverse_dict[reverse_word] += 1\n else:\n reverse_dict[word] = 1\n\n return pairs\n```\n![Screen Shot 2023-10-19 at 21.29.06.png](https://assets.leetcode.com/users/images/d30ceb3f-16f8-4f4f-badb-3c1bc5f5672f_1697732990.1202688.png)\n\n# Memory 13 MB Beats \uD83D\uDCC999.67%\n\n```\nclass Solution(object):\n def maximumNumberOfStringPairs(self, words):\n arr = []\n for i in words:\n demo_arr = []\n for j in words:\n if i[::-1] == j or i == j:\n demo_arr.append(j)\n if len(demo_arr) > 1:\n arr.append(demo_arr)\n return int(len(arr) / 2)\n```\n![Screen Shot 2023-10-19 at 21.28.50.png](https://assets.leetcode.com/users/images/efc52bb4-bf9a-41f4-83fb-3bdaac946246_1697732959.5790963.png)\n\n# \u2B06\uFE0F Please upvote \u2B06\uFE0F\n\n\n\n\n
6
0
['Python']
0
find-maximum-number-of-string-pairs
Java Solution || Using StringBuilder
java-solution-using-stringbuilder-by-ank-vjyz
Intuition\n Describe your first thoughts on how to solve this problem. \nWe have to find whether the reverse of a string at words[i] is present at index j such
Ankur_Chhillar
NORMAL
2023-07-08T15:15:16.909704+00:00
2023-07-08T15:15:16.909738+00:00
478
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWe have to find whether the reverse of a string at words[i] is present at index j such that 0<=i<j<words.length and return the count of such pairs found.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nI have used two for loops one from i=0 to words.length and inside it from j=i+1 to words.length and stored the words[j] in a string builder and compared it to the words[i] by reversing the one at index j and after the comparison has taken place then emtpying the stringbuilder so that new string can be stored in it.\n\n# Code\n```\nclass Solution {\n public int maximumNumberOfStringPairs(String[] words) {\n int count = 0;\n StringBuilder sb = new StringBuilder();\n for(int i=0;i<words.length;i++){\n for(int j=i+1;j<words.length;j++){\n sb.append(words[j]);\n if(words[i].equals(sb.reverse().toString())){\n count++;\n }\n sb.delete(0,sb.length());\n }\n }\n return count;\n }\n}\n```\n\n![oie_CksRiTNvbciG.jpg](https://assets.leetcode.com/users/images/789fb96d-4a96-464c-a4ee-ea8b1f844689_1688829277.9101799.jpeg)
6
0
['Java']
1
find-maximum-number-of-string-pairs
Simple Java with Iterator
simple-java-with-iterator-by-dafteeer-hj7l
Approach\nI used Iterator and StringBuffer.reverse() for easy and simple solution.\n\n# Code\n\nclass Solution {\n public int maximumNumberOfStringPairs(Stri
dafteeer
NORMAL
2023-07-08T21:04:44.059144+00:00
2023-07-08T21:04:44.059166+00:00
662
false
# Approach\nI used Iterator and StringBuffer.reverse() for easy and simple solution.\n\n# Code\n```\nclass Solution {\n public int maximumNumberOfStringPairs(String[] words) {\n List<String> wordsList = new ArrayList(Arrays.asList(words));\n int count = 0;\n for (Iterator<String> wordsIterator = wordsList.iterator(); wordsIterator.hasNext();) {\n String word = wordsIterator.next();\n wordsIterator.remove();\n if (wordsList.contains(reverse(word))) count++;\n }\n return count;\n }\n\n private String reverse(String input) {\n return new StringBuffer(input).reverse().toString();\n }\n}\n```
5
0
['String', 'Iterator', 'Java']
1
find-maximum-number-of-string-pairs
Easy Python Solution
easy-python-solution-by-vistrit-qc01
Code\n\nclass Solution:\n def maximumNumberOfStringPairs(self, words: List[str]) -> int:\n c=0\n for i in range(len(words)):\n for j
vistrit
NORMAL
2023-06-27T18:24:46.564103+00:00
2023-06-27T18:24:46.564132+00:00
976
false
# Code\n```\nclass Solution:\n def maximumNumberOfStringPairs(self, words: List[str]) -> int:\n c=0\n for i in range(len(words)):\n for j in range(i+1,len(words)):\n if words[i]==words[j][::-1]:\n c+=1\n return c\n```
5
0
['Python3']
2
find-maximum-number-of-string-pairs
[C++] Set Vs. Hashing String to Int Vs. Bitmask Hashing, 4ms, 20.5MB
c-set-vs-hashing-string-to-int-vs-bitmas-eqck
Let\'s start with the simplest approach, which means we will use a hashset (seen) to keep track of already encountered strings.\n\nMore specifically, we will st
Ajna2
NORMAL
2023-06-24T20:39:20.946592+00:00
2023-06-24T20:39:20.946616+00:00
308
false
Let\'s start with the simplest approach, which means we will use a hashset (`seen`) to keep track of already encountered strings.\n\nMore specifically, we will start declaring:\n* `res` as our usual counter variable, initially set to be `0`;\n* `seen`, our set where we will store what we already saw (or its reverse, in the second version of this solution down below).\n\nFor each `word` in `words`, we will:\n* store the original `word` in `orig`;\n* swap its first and second character;\n* check if we have ever seen the newly reversed `word` in `seen` and, if so, increase `res` by `1`;\n* store `orig` in `seen`.\n\nFinally, we will `return` `res`.\n\n# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n```cpp\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(vector<string> &words) {\n // suppor variables\n int res = 0;\n unordered_set<string> seen;\n // parsing words\n for (string &word: words) {\n string orig = word;\n swap(word[0], word[1]);\n if (seen.find(word) != end(seen)) res++;\n seen.insert(orig);\n }\n return res;\n }\n};\n```\n\nWe can actually play a bit smarter here and look up for the word itself, then store just the reverse of it, having to use `tmp` all the time:\n\n# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(n)$$\n\n# Code\n\n```cpp\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(vector<string> &words) {\n // suppor variables\n int res = 0;\n unordered_set<string> seen;\n // parsing words\n for (string &word: words) {\n if (seen.find(word) != end(seen)) res++;\n swap(word[0], word[1]);\n seen.insert(word);\n }\n return res;\n }\n};\n```\n\nBut we can do better if we just consider that we have an alphabet of only `26` characters, and each word will only be `2` characters - so we can hash each string counting in base `26`, for a grant total of `26 * 26 == 676` cells.\n\nWe can then hash each word into an `int` and do way quicker checks about what we have seen before or not (albeit with potentially higher initialisation costs for `seen` with smaller sets of words).\n\nNotice we might actually optimise a bit more, space-wise, if we consider that strings like `"aa"`, `"bb"`, `"cc"`, etc. have no place being considered and since they appear every `27` positions, proceeding lexicographically, we might adjust our hashing by subtracting its value `/ 27`, but not really worth all the cost to save a handful of bites.\n\n# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```cpp\nconstexpr int maxRange = 676;\n\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(vector<string> &words) {\n // suppor variables\n int res = 0, tmp;\n bool seen[maxRange] = {};\n // parsing words\n for (string &word: words) {\n tmp = (word[0] - \'a\') * 26 + word[1] - \'a\';\n if (seen[tmp]) res++;\n seen[(word[1] - \'a\') * 26 + word[0] - \'a\'] = true;\n }\n return res;\n }\n};\n```\n\nSame core logic, but hashing getting the value of each character with a bitmask (`\'a\' & 31` is `1`, `\'b\' & 31` is `2`, and so on), using `5` bits for each digits (since they are enough to represent values up to `31`, so fully within our range), which makes `10` bits total or, in other words, `1024` slots in `seen`.\n\nAgain, not a major increment with the small values we are dealing with, but still maybe a tad faster and a lot of fun to handle.\n\n# Complexity\n- Time complexity: $$O(n)$$\n- Space complexity: $$O(1)$$\n\n# Code\n```cpp\nconstexpr int maxRange = 1024, bitmask = 31;\n\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(vector<string> &words) {\n // suppor variables\n int res = 0, tmp;\n bool seen[maxRange] = {};\n // parsing words\n for (string &word: words) {\n tmp = ((word[0] & bitmask) << 5) + (word[1] & bitmask);\n if (seen[tmp]) res++;\n seen[((word[1] & bitmask) << 5) + (word[0] & bitmask)] = true;\n }\n return res;\n }\n};\n```
5
0
['String', 'Bit Manipulation', 'Hash Function', 'Bitmask', 'C++']
1
find-maximum-number-of-string-pairs
Simple || Short || Clean || Java Solution
simple-short-clean-java-solution-by-hima-qrcj
\njava []\nclass Solution {\n public int maximumNumberOfStringPairs(String[] words) {\n Map<String, Integer> map = new HashMap<>();\n for (Stri
HimanshuBhoir
NORMAL
2023-06-24T16:04:08.759853+00:00
2023-06-24T16:04:35.217089+00:00
2,007
false
\n```java []\nclass Solution {\n public int maximumNumberOfStringPairs(String[] words) {\n Map<String, Integer> map = new HashMap<>();\n for (String s : words) {\n String rev = new StringBuilder(s).reverse().toString();\n if(map.containsKey(rev)) map.put(rev, map.get(rev)+1);\n else map.put(s,0);\n }\n int ans = 0;\n for(int value : map.values()) ans += value;\n return ans;\n }\n}\n\n```
5
1
['Java']
2
find-maximum-number-of-string-pairs
Best and simple java approach
best-and-simple-java-approach-by-venkate-9rvz
Code\njava []\nclass Solution {\n public int maximumNumberOfStringPairs(String[] words) {\n int ans=0;\n for(int i=0;i<words.length;i++) {\n
VenkateshThantapureddy
NORMAL
2024-09-07T09:15:56.647899+00:00
2024-09-07T09:15:56.647937+00:00
155
false
# Code\n```java []\nclass Solution {\n public int maximumNumberOfStringPairs(String[] words) {\n int ans=0;\n for(int i=0;i<words.length;i++) {\n \tfor(int j=i+1;j<words.length;j++) {\n \t\tif(words[i].charAt(0)==words[j].charAt(1) && words[i].charAt(1)==words[j].charAt(0)) \n \t\t\tans++;\n \t}\n }\n return ans;\n }\n}\n```
4
0
['Java']
0
find-maximum-number-of-string-pairs
Good To Go ✅🚀
good-to-go-by-dixon_n-v7o0
\n# Code\njava []\n\n// This approcah is used to solve 2131. Longest Palindrome by Concatenating Two Letter Words\n\n\nclass Solution {\n public int maximumN
Dixon_N
NORMAL
2024-08-03T00:35:32.923307+00:00
2024-08-03T00:35:32.923339+00:00
473
false
\n# Code\n```java []\n\n// This approcah is used to solve 2131. Longest Palindrome by Concatenating Two Letter Words\n\n\nclass Solution {\n public int maximumNumberOfStringPairs(String[] words) {\n int ans = 0;\n HashMap<String, Integer> map = new HashMap<>();\n \n for (String w : words) {\n // Reverse the current string\n StringBuilder reversed = new StringBuilder(w).reverse();\n String reversedStr = reversed.toString();\n \n // Check if the reversed string exists in the map\n if (map.getOrDefault(reversedStr, 0) > 0) {\n ans++;\n map.put(reversedStr, map.get(reversedStr) - 1);\n } else {\n map.put(w, map.getOrDefault(w, 0) + 1);\n }\n }\n \n return ans;\n }\n}\n\n\n```
4
0
['Hash Table', 'Java']
4
find-maximum-number-of-string-pairs
One line solution with Runtime 98%
one-line-solution-with-runtime-98-by-smd-3rdm
\n\n/**\n * @param {string[]} words\n * @return {number}\n */\nvar maximumNumberOfStringPairs = function(words) {\n return words.length - new Set(words.map((a)
smd_94
NORMAL
2023-11-13T20:44:04.765751+00:00
2023-11-13T20:44:04.765773+00:00
678
false
\n```\n/**\n * @param {string[]} words\n * @return {number}\n */\nvar maximumNumberOfStringPairs = function(words) {\n return words.length - new Set(words.map((a) => a[0]>a[1]? a[0]+a[1]: a[1]+a[0] )).size;\n};\n```
4
0
['JavaScript']
1
find-maximum-number-of-string-pairs
Easy Peasy
easy-peasy-by-ridamexe-3ofq
Code\n\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(vector<string>& words) {\n int count=0;\n int n=words.size();\n\n for
ridamexe
NORMAL
2023-06-25T13:41:52.677295+00:00
2023-06-25T13:41:52.677315+00:00
393
false
# Code\n```\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(vector<string>& words) {\n int count=0;\n int n=words.size();\n\n for(int i=0; i<n-1; i++){\n string s1=words[i];\n\n for(int j=i+1; j<n; j++){\n string s2=words[j];\n\n if(s1[0]==s2[1] and s1[1]==s2[0]) count++; \n }\n }\n return count;\n \n }\n};\n```
4
0
['C++']
1
find-maximum-number-of-string-pairs
1 line using Set
1-line-using-set-by-bariscan97-r9s5
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
Bariscan97
NORMAL
2023-06-24T23:54:56.667411+00:00
2023-06-24T23:54:56.667440+00:00
787
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:\n def maximumNumberOfStringPairs(self, words: List[str]) -> int:\n return len(words)-len({f"{sorted(i)}" for i in words})\n \n \n```
4
0
['Hash Table', 'Python', 'Python3']
2
find-maximum-number-of-string-pairs
Java || O(N) runtime, O(N) space || Scalable solution using StringBuilder.reverse()
java-on-runtime-on-space-scalable-soluti-fpe0
O(N) runtime due to iteration through words.\nO(N) space due to HashSet wordSet that may go up to N, the input words length.\n\nPairs are unique so removing fro
ZionWilliamson1
NORMAL
2023-06-24T16:23:51.857262+00:00
2023-06-24T16:23:51.857289+00:00
1,085
false
O(N) runtime due to iteration through `words`.\nO(N) space due to HashSet `wordSet` that may go up to N, the input `words` length.\n\nPairs are unique so removing from HashSet is never needed.\n```\nclass Solution {\n public int maximumNumberOfStringPairs(String[] words) {\n int maxPairs = 0;\n \n //Iterate through words and insert them into a HashSet\n //At each word, check if you have seen it\'s reverse\n Set<String> wordSet = new HashSet<>();\n \n for(String word : words) {\n StringBuilder sb = new StringBuilder(word);\n String reversedWord = sb.reverse().toString();\n \n //We have seen the reverse here, so we increment a pair has been found\n\t\t\t//contains() check is O(1) runtime\n if(wordSet.contains(reversedWord)) {\n maxPairs++;\n }\n \n //Always add a word that we have run across\n wordSet.add(word);\n }\n \n return maxPairs;\n }\n}\n```
4
0
['Java']
5
find-maximum-number-of-string-pairs
🔥MAP🔥||🔥C++🔥||🔥MOST SIMPLE🔥||🔥EASY TO UNDERSTAND🔥
mapcmost-simpleeasy-to-understand-by-gan-90r2
if this code helps you, please upvote\n# Code\n\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(vector<string>& words) {\n int ans = 0;\n
ganeshkumawat8740
NORMAL
2023-06-24T16:04:39.465737+00:00
2023-06-25T01:38:02.078879+00:00
803
false
# if this code helps you, please upvote\n# Code\n```\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(vector<string>& words) {\n int ans = 0;\n unordered_map<string,int> mp;\n string s;\n for(auto &i: words){\n s = i;\n reverse(s.begin(),s.end());\n if(mp.count(s)){\n ans++;\n mp.erase(i);\n }else{\n mp[i]++;\n }\n }\n return ans;\n }\n};\n```
4
0
['Hash Table', 'String', 'String Matching', 'C++']
0
find-maximum-number-of-string-pairs
1 ms Beats 100.00% of users with Java
1-ms-beats-10000-of-users-with-java-by-h-a2gj
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
hojiakbarmadaminov45
NORMAL
2024-02-23T14:49:17.197847+00:00
2024-02-23T14:49:17.197875+00:00
288
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: 1ms \n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: 41.40 mb\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public int maximumNumberOfStringPairs(String[] words) {\n int count = 0;\n for (int i = 0; i< words.length; i++){\n\n for(int j=i+1; j<words.length; j++){\n \n if(words[i].charAt(0) == words[j].charAt(1) && words[i].charAt(1) == words[j].charAt(0))count++;\n }\n }\n return count;\n }\n}\n```
3
0
['Java']
0
find-maximum-number-of-string-pairs
String Pairs - JavaScript - Beats 99.46 % ( 56 ms ) 🔥
string-pairs-javascript-beats-9946-56-ms-37is
\n\n1. Solution with two for loops\n\n/**\n * @param {string[]} words\n * @return {number}\n */\nvar maximumNumberOfStringPairs = function(words) {\n count =
zemamba
NORMAL
2023-06-26T20:03:52.920086+00:00
2023-06-26T23:49:41.039596+00:00
397
false
![image.png](https://assets.leetcode.com/users/images/5387b061-43d8-4eb2-ad68-62c894a3d6f3_1687823172.9767308.png)\n\n1. Solution with two for loops\n```\n/**\n * @param {string[]} words\n * @return {number}\n */\nvar maximumNumberOfStringPairs = function(words) {\n count = 0 \n\n for (let i = 0; i < words.length; i++) \n for (let j = i + 1; j < words.length; j++) \n if (words[i][0] == words[j][1])\n if (words[i][1] == words[j][0])\n count ++ \n \n return count\n};\n```\n2. Solution with Hash Table\n```\n/**\n * @param {string[]} words\n * @return {number}\n */\nvar maximumNumberOfStringPairs = function(words) {\n count = 0 \n obj = {}\n \n for (word of words) {\n reverse = word[1] + word[0] \n\n if (obj[reverse] == true) count ++\n\n obj[word] = true \n } \n \n return count\n};\n```\nPlease put likes, leave comments, share my solution, I try to find the best solutions)
3
0
['Hash Table', 'JavaScript']
1
find-maximum-number-of-string-pairs
C++ -> Brute Force -> Set Solution [2 Solution]
c-brute-force-set-solution-2-solution-by-56w1
Intuition\nThink of reverse the each words of the given string and check if the reverse words available or not.\n\n---\n\n\n# Complexity\n- Time complexity:\n1.
amit24x
NORMAL
2023-06-24T17:08:30.976141+00:00
2023-06-24T17:08:30.976173+00:00
702
false
# Intuition\nThink of reverse the each words of the given string and check if the reverse words available or not.\n\n---\n\n\n# Complexity\n- Time complexity:\n1. *Brute Force:* **O(n^2)**\n2. *Set:* **O(n)**\n\n- Space complexity:**O(n)**\n\n---\n\n\n**Solution 1 - Brute Force**\n\n```\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(vector<string>& words) {\n int n = words.size();\n vector<string> rev;\n for(int i=0;i<n;i++)\n {\n string str = words[i];\n reverse(str.begin(),str.end());\n rev.push_back(str);\n }\n int ans = 0;\n for(int i=0;i<n;i++)\n {\n for(int j=0;j<n;j++)\n {\n if(words[i] == rev[j] && i!=j)\n {\n ans++;\n }\n }\n }\n return ans/2;\n }\n};\n```\n\n---\n\n\n**Solution 2 - Set**\n```\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(vector<string>& words) {\n unordered_set<string> s;\n int r = 0;\n for (string &word : words) {\n sort(word.begin(), word.end());\n r += !s.insert(word).second;\n }\n return r; \n }\n};\n```\n\n![upvote.jpeg](https://assets.leetcode.com/users/images/970e1476-e7e6-4150-8f2c-33d33fac059f_1687626500.9282358.jpeg)\n
3
0
['C++']
0
find-maximum-number-of-string-pairs
JavaScript simple solution with explanation
javascript-simple-solution-with-explanat-gqh1
Approach\n\n1. Initialize maxPairs to keep track of the maximum number of pairs\n2. Initialize wordSet to track words that can potentially form pairs\n3. Iterat
js_pro
NORMAL
2023-06-24T16:03:51.384912+00:00
2023-08-29T10:10:36.201827+00:00
408
false
# Approach\n\n1. Initialize `maxPairs` to keep track of the maximum number of pairs\n2. Initialize `wordSet` to track words that can potentially form pairs\n3. Iterate through the words:\n - sort the word lexicographically\n - checks if it is in `wordSet`\n - if found, a pair is formed, increment `maxPairs` and remove the word from the set\n - otherwise, add the word to the set\n4. Return `maxPairs`\n\n# Complexity\n\n- Time Complexity: `O(n)` - It iterates through the array once.\n- Space Complexity: `O(n)` - In the worst case, all words could be added to the set.\n\n# Code\n```\n/**\n * @param {string[]} words\n * @return {number}\n */\nconst maximumNumberOfStringPairs = function (words) {\n let maxPairs = 0;\n const wordSet = new Set();\n\n for (let i = 0; i < words.length; i++) {\n const w = words[i][0] > words[i][1] \n ? words[i][1] + words[i][0] \n : words[i];\n\n if (wordSet.has(w)) {\n maxPairs++;\n wordSet.delete(w);\n } else {\n wordSet.add(w);\n }\n }\n return maxPairs;\n};\n```
3
0
['JavaScript']
1
find-maximum-number-of-string-pairs
100% beat in java very easy code for beginners 😊.
100-beat-in-java-very-easy-code-for-begi-kmgn
Code
Galani_jenis
NORMAL
2025-01-07T12:43:08.929376+00:00
2025-01-07T12:43:08.929376+00:00
269
false
![94da60ee-7268-414c-b977-2403d3530840_1725903127.9303432.png](https://assets.leetcode.com/users/images/e13b2d25-1a97-4584-87df-979af55fed1d_1736253640.4995627.png) # Code ```java [] class Solution { public int maximumNumberOfStringPairs(String[] words) { int ans = 0; for (int i = 0; i < words.length - 1; i++) { for (int j = i + 1; j < words.length; j++) { // Check if words are identical or if they are pairs that are reversals of each other if ( words[i] == words[j] || (words[i].charAt(0) == words[j].charAt(1) && words[i].charAt(1) == words[j].charAt(0) ) ) { ans++; } } } return ans; } } ```
2
0
['Java']
1
find-maximum-number-of-string-pairs
EASY C++ SOLUTION || 100% BEATS || 0 ms
easy-c-solution-100-beats-0-ms-by-yash_a-jxbu
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
Yash_Akabari
NORMAL
2024-08-20T15:30:57.386323+00:00
2024-08-20T15:30:57.386369+00:00
97
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- O(N)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n- O(N)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(vector<string>& words) {\n unordered_set<string> set;\n int count = 0;\n for(int i =0;i<words.size();i++){\n string str = words[i];\n string rev = str;\n reverse(rev.begin(),rev.end());\n if(set.contains(rev)){\n count++;\n set.erase(rev);\n }\n else set.insert(str);\n }\n return count;\n }\n};\n```
2
0
['Array', 'Hash Table', 'C++']
0
find-maximum-number-of-string-pairs
✅ One Line Solution
one-line-solution-by-mikposp-2avr
Code #1\nTime complexity: O(n). Space complexity: O(n).\n\nclass Solution:\n def maximumNumberOfStringPairs(self, w: List[str]) -> int:\n return len(w
MikPosp
NORMAL
2024-05-12T11:52:07.303409+00:00
2024-05-12T11:52:07.303443+00:00
140
false
# Code #1\nTime complexity: $$O(n)$$. Space complexity: $$O(n)$$.\n```\nclass Solution:\n def maximumNumberOfStringPairs(self, w: List[str]) -> int:\n return len(w)-len({*map(frozenset,w)})\n```\n\n# Code #2\nTime complexity: $$O(n)$$. Space complexity: $$O(n)$$.\n```\nclass Solution:\n def maximumNumberOfStringPairs(self, w: List[str]) -> int:\n return len(w)-len({min(v)+max(v) for v in w})\n```\n\n# Code #3\nTime complexity: $$O(n)$$. Space complexity: $$O(n)$$.\n```\nclass Solution:\n def maximumNumberOfStringPairs(self, w: List[str]) -> int:\n return len({*w}&{v[::-1] for v in w if v!=v[::-1]})//2\n```\n\n# Code #4\nTime complexity: $$O(n^2)$$. Space complexity: $$O(1)$$.\n```\nclass Solution:\n def maximumNumberOfStringPairs(self, w: List[str]) -> int:\n return sum(v[::-1] in w[i+1:] for i,v in enumerate(w))\n```
2
0
['Array', 'Hash Table', 'String', 'Simulation', 'Python', 'Python3']
0
find-maximum-number-of-string-pairs
[Java] Easy 100% solution
java-easy-100-solution-by-ytchouar-9e0p
java\nclass Solution {\n public int maximumNumberOfStringPairs(final String[] words) {\n int count = 0;\n\n for (int i = 0; i< words.length; i+
YTchouar
NORMAL
2024-05-05T04:08:50.605584+00:00
2024-05-05T04:08:50.605601+00:00
231
false
```java\nclass Solution {\n public int maximumNumberOfStringPairs(final String[] words) {\n int count = 0;\n\n for (int i = 0; i< words.length; i++)\n for(int j=i+1; j<words.length; j++)\n if(words[i].charAt(0) == words[j].charAt(1) && words[i].charAt(1) == words[j].charAt(0))\n count++;\n\n return count;\n }\n}\n```
2
0
['Java']
1
find-maximum-number-of-string-pairs
🔒 Use constraints to solve with vector of size 677 🔢
use-constraints-to-solve-with-vector-of-j22go
Intuition\nThe problem seems to involve counting pairs of words in a given list of strings. Each word in the list is potentially paired with its reverse. The ob
sambhav22435
NORMAL
2024-04-06T06:30:23.274279+00:00
2024-04-06T06:30:23.274307+00:00
97
false
# Intuition\nThe problem seems to involve counting pairs of words in a given list of strings. Each word in the list is potentially paired with its reverse. The objective is to find the maximum number of such pairs that can be formed.\n\n# Approach\n1. We\'ll iterate through the list of words, counting occurrences of each word and its reverse.\n2. To avoid counting duplicates (like palindromes), we\'ll check if the reversed word is different from the original word before counting it.\n3. We\'ll store the counts in a vector.\n4. After counting, we\'ll iterate through the counts vector and count the number of pairs that have occurred at least twice.\n5. Finally, we\'ll return half of this count, as each pair has been counted twice.\n\n# Complexity\n- Time complexity: \n - Counting occurrences of each word and its reverse takes O(n), where n is the number of words.\n - Iterating through the counts vector takes O(677), which is a constant time operation.\n - Overall, the time complexity is O(n).\n\n- Space complexity:\n - We use a vector to store counts, which has a fixed size of 677.\n - The space complexity is therefore O(1), as it doesn\'t depend on the size of the input.\n\n# Code\n```cpp []\n#include <vector>\n#include <string>\n#include <algorithm> // for std::reverse\n\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(std::vector<std::string>& words) {\n std::vector<int> ans(677, 0); // Initialize vector to store counts\n\n // Count occurrences of each word and its reverse\n for (int i = 0; i < words.size(); ++i) {\n int index = stringtoindex(words[i]);\n ans[index]++; // Increment count for original word\n\n std::string reversed = words[i];\n std::reverse(reversed.begin(), reversed.end()); // Reverse the word\n if (reversed != words[i]) { // Avoid counting duplicates\n ans[stringtoindex(reversed)]++; // Increment count for reversed word\n }\n }\n\n int cnt = 0;\n for (int i = 0; i < 677; ++i) {\n if (ans[i] >= 2) {\n cnt++; // Increment count for each pair found\n }\n }\n\n return cnt/2;\n }\n\nprivate:\n int stringtoindex(const std::string& str) {\n int index = (str[0] - \'a\') * 26 + (str[1] - \'a\');\n return index;\n }\n\n std::string stringtoindex(int index) {\n std::string str;\n str.push_back(\'a\' + index / 26);\n str.push_back(\'a\' + index % 26);\n return str;\n }\n};\n\n```
2
0
['Array', 'Hash Table', 'Hash Function', 'C++']
0
find-maximum-number-of-string-pairs
Java || Simple string solution ♨️♨️
java-simple-string-solution-by-ritabrata-tara
\n\n# Code\n\nclass Solution {\n public int maximumNumberOfStringPairs(String[] words) {\n List<String> list = new ArrayList<>();\n StringBuild
Ritabrata_1080
NORMAL
2023-11-03T18:37:13.768094+00:00
2023-11-03T18:37:13.768123+00:00
119
false
\n\n# Code\n```\nclass Solution {\n public int maximumNumberOfStringPairs(String[] words) {\n List<String> list = new ArrayList<>();\n StringBuilder sb = new StringBuilder();\n int count = 0;\n for(String p : words){\n char c[] = p.toCharArray();\n if(c[0] != c[1]){\n sb.append(c[1]);\n sb.append(c[0]);\n list.add(sb.toString());\n sb.setLength(0);\n }\n }\n List<String> list1 = new ArrayList<>();\n for(String p : words){\n list1.add(p);\n }\n for(String p : list1){\n if(list.contains(p)){\n list.remove(p);\n count += 1;\n }\n }\n return (count <=1)?count:count/2;\n }\n}\n\n```
2
0
['String', 'Java']
0
find-maximum-number-of-string-pairs
100% and 78% beats | Java Solution
100-and-78-beats-java-solution-by-s_u_04-hofa
\nclass Solution \n{\n public int maximumNumberOfStringPairs(String[] words) \n {\n // creating a dic for each unique pair(26 * 26)\n boolea
S_U_04
NORMAL
2023-10-02T20:11:36.208835+00:00
2023-10-12T19:02:53.370126+00:00
496
false
```\nclass Solution \n{\n public int maximumNumberOfStringPairs(String[] words) \n {\n // creating a dic for each unique pair(26 * 26)\n boolean[] dictionary = new boolean[676];\n int count = 0;\n\n for (String w : words) \n {\n // current word index\n int pairIndex1 = w.charAt(0) - \'a\' + (w.charAt(1) - \'a\') * 26;\n // reversed word index\n int pairIndex2 = w.charAt(1) - \'a\' + (w.charAt(0) - \'a\') * 26;\n\n // checking if reversed word already encountered before or not?\n count += dictionary[pairIndex2] ? 1 : 0;\n // encountering current word\n dictionary[pairIndex1] = true;\n }\n\n return count;\n }\n}\n```
2
0
['Java']
0
find-maximum-number-of-string-pairs
Find Maximum Number Of String Pairs Solution in C++
find-maximum-number-of-string-pairs-solu-2n3q
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \nUsing Unordered map\n#
The_Kunal_Singh
NORMAL
2023-09-15T18:08:13.615655+00:00
2023-09-15T18:08:13.615691+00:00
42
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nUsing Unordered map\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\nO(n^2)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(n)\n# Code\n```\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(vector<string>& words) {\n unordered_map<string, string> mp;\n int i, count=0;\n for(i=0 ; i<words.size() ; i++)\n {\n string str = words[i];\n reverse(str.begin(), str.end());\n if(mp.find(str)!=mp.end())\n {\n mp[str] = words[i];\n count++;\n }\n else\n {\n mp[words[i]] = "";\n }\n }\n return count;\n }\n};\n```\n![upvote new.jpg](https://assets.leetcode.com/users/images/0933a2a5-9a92-4f43-a9a0-46eeda81e2b2_1694801285.4025972.jpeg)\n
2
0
['C++']
0
find-maximum-number-of-string-pairs
Easy Java solution - Beats 100%
easy-java-solution-beats-100-by-karansid-tepv
We can use a nested for-loop to iterate through our \'words\' array and compare any two words in our array without worrying about it being counted as a duplicat
karansidz
NORMAL
2023-08-24T22:40:52.024645+00:00
2023-08-24T22:40:52.024665+00:00
148
false
We can use a nested for-loop to iterate through our \'words\' array and compare any two words in our array without worrying about it being counted as a duplicate (because the second for loop starts at \'i+1\' to ensure it can not be compared again). \n We can make use of String\'s charAt function to compare the characters. Since we are dealing with Strings of length 2, we can use charAt to compare the 1st character of one word with the 2nd character of the other word (We cannot use String.reverse or any similar functionality because Strings are not mutable in Java). If the comparison works, increment the pairs variable and return it at the end of the nested for loop.\n\n\n\n\n# Code\n```\nclass Solution {\n public int maximumNumberOfStringPairs(String[] words) {\n int pairs = 0;\n for (int i = 0; i < words.length; i++) {\n for (int j = i + 1; j < words.length; j++) {\n if (words[i].charAt(0) == words[j].charAt(1) && words[i].charAt(1) == words[j].charAt(0)) {\n pairs++;\n }\n }\n }\n return pairs;\n }\n}\n```
2
0
['Java']
0
find-maximum-number-of-string-pairs
Finding Maximum Number of String Pairs
finding-maximum-number-of-string-pairs-b-lj67
Intuition\n Describe your first thoughts on how to solve this problem. \nWHEN I SEE THIS PROBLEM: Find Maximum Number of (String Pairs)\n\n\n\n# Code\n\n\nclass
aadhiganapathy8
NORMAL
2023-08-16T11:59:54.131224+00:00
2023-08-16T11:59:54.131251+00:00
626
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nWHEN I SEE THIS PROBLEM: Find Maximum Number of (String Pairs)\n![image.png](https://assets.leetcode.com/users/images/da4fa02d-8240-425d-9ee7-93b95966a1ed_1692186832.7186623.png)\n\n\n# Code\n```\n\nclass Solution {\n public int maximumNumberOfStringPairs(String[] words) {\n ArrayList<String> obj=new ArrayList<String>();\n Collections.addAll(obj,words);\n int count=0;\n for(int i=0;i<words.length;i++){\n String str=words[i];\n int n=str.length();\n String ktr="";\n //REVERSE\n for(int k=0;k<n;k++){\n ktr=str.charAt(k)+ktr;\n }\n //REMOVE ELEMENTS LIKE "ZZ","aa"\n if(ktr.equals(str)){\n obj.remove(ktr);\n }\n //REMOVE ELEMENTS IF PRESENT IN ARRAY LIST\n if(obj.contains(ktr)){\n obj.remove(str); \n count++;\n }\n \n \n \n }\n \n return count;\n }\n} \n```
2
0
['Array', 'Java']
1
find-maximum-number-of-string-pairs
Simple Solution using Hash map . Easy to understand for Beginners . Beats about 99 % .
simple-solution-using-hash-map-easy-to-u-xvjr
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
BinaryBrawler
NORMAL
2023-08-07T02:02:06.160134+00:00
2023-08-07T02:02:06.160162+00:00
622
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![Screenshot from 2023-08-07 07-01-17.png](https://assets.leetcode.com/users/images/7258eb3a-f009-4df7-a514-c0ecc1501da6_1691373718.0283215.png)\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def maximumNumberOfStringPairs(self, words: List[str]) -> int:\n from collections import defaultdict\n dict_ = defaultdict(int)\n for i,word in enumerate(words):\n dict_[word[::-1]] = i\n pairs = 0\n extra = []\n for i,element in enumerate(words):\n if element in dict_ and dict_[element] != i and element not in extra:\n pairs += 1\n extra.append(element[::-1])\n else:\n continue\n return pairs\n```
2
0
['Python3']
1
find-maximum-number-of-string-pairs
Java || 1ms run:O(n) mem:O(1) || Boolean flags, No HashMap
java-1ms-runon-memo1-boolean-flags-no-ha-9paz
\nclass Solution {\n public int maximumNumberOfStringPairs(String[] words) {\n boolean[] found = new boolean[26 * 26];\n int pairCount = 0;\n
dudeandcat
NORMAL
2023-08-02T07:10:16.223568+00:00
2023-08-02T07:10:16.223607+00:00
261
false
```\nclass Solution {\n public int maximumNumberOfStringPairs(String[] words) {\n boolean[] found = new boolean[26 * 26];\n int pairCount = 0;\n for (String s : words) {\n if (found[(s.charAt(1) - \'a\') * 26 + s.charAt(0) - \'a\']) pairCount++;\n found[(s.charAt(0) - \'a\') * 26 + s.charAt(1) - \'a\'] = true;\n }\n return pairCount;\n }\n}\n```
2
0
[]
1
find-maximum-number-of-string-pairs
Easy Approach
easy-approach-by-noor88-2qwq
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
Noor88
NORMAL
2023-07-24T18:48:05.580157+00:00
2023-07-24T18:48:05.580178+00:00
163
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 {\n public int maximumNumberOfStringPairs(String[] words)\n\t\t{\n\t\t\tint count=0;\n\t\t\tint n=words.length;\n\t\t\tfor(int i = 0; i < n; i++)\n\t\t\t{\n for(int j = i + 1; j < n; j++)\n\t\t\t\t\t{\n if(words[i].charAt(0) == words[j].charAt(1) && words[i].charAt(1) == words[j].charAt(0))\n\t\t\t\t\t\t{\n count++;\n\t\t\t\t\t\t}\n\t\t\t\t\t}\n\t\t\t}\n\t\t\treturn count;\n\t\t}\n}\n```
2
0
['Java']
0
find-maximum-number-of-string-pairs
2 C++ solutions || Using hash-map and hash-set approach || Beats 100% !!
2-c-solutions-using-hash-map-and-hash-se-w7wc
Code\n\n// Soution 1 (HashMap)\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(vector<string>& words) {\n unordered_map<string, int> mp;\n
prathams29
NORMAL
2023-07-19T09:19:26.712972+00:00
2023-07-19T09:19:26.713002+00:00
133
false
# Code\n```\n// Soution 1 (HashMap)\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(vector<string>& words) {\n unordered_map<string, int> mp;\n int ans = 0;\n for(auto i : words){\n string rev = i;\n reverse(rev.begin(), rev.end());\n if(mp[rev] > 0)\n ans++, mp[rev]--;\n else\n mp[i]++;\n }\n return ans;\n }\n};\n\n// Solution 2 (Using HashSet, beats 100%)\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(vector<string>& words) {\n unordered_set<string> s;\n int ans = 0;\n for(auto i : words){\n string rev = i;\n reverse(rev.begin(), rev.end());\n if(s.find(rev) == s.end())\n s.insert(i);\n else\n ans++;\n }\n return ans;\n }\n};\n```
2
0
['Hash Table', 'C++']
0
find-maximum-number-of-string-pairs
Easy c++ solution using linear search.
easy-c-solution-using-linear-search-by-j-y1pi
Intuition\n\n# Approach\nBrute Force Solution:\nUsing two loops firstly reverse the string of words and compare string of entire words.\n\n# Complexity\n- Time
jhasudarshan_07
NORMAL
2023-07-15T14:18:23.411509+00:00
2023-07-15T14:18:23.411537+00:00
288
false
# Intuition\n\n# Approach\nBrute Force Solution:\nUsing two loops firstly reverse the string of words and compare string of entire words.\n\n# Complexity\n- Time complexity:O(n^2)\n\n- Space complexity:O(n)\n\n# Code\n```\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(vector<string>& words) {\n string s;\n int count = 0;\n for(int i=0;i<words.size()-1;i++)\n {\n for(int j=i+1;j<words.size();j++)\n {\n s = words[j];\n reverse(s.begin(),s.end());\n if(words[i]==s) count++;\n }\n }\n return count;\n }\n};\n```
2
0
['C++']
0
find-maximum-number-of-string-pairs
Q2744 Accepted C++ ✅ HashMap O(n) | Easiest Method
q2744-accepted-c-hashmap-on-easiest-meth-m3au
\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(vector<string>& words) {\n int n = words.size();\n int count = 0;\n unorder
adityasrathore
NORMAL
2023-07-09T10:07:33.492173+00:00
2023-07-09T10:07:33.492193+00:00
176
false
```\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(vector<string>& words) {\n int n = words.size();\n int count = 0;\n unordered_map <string,int> mp;\n for(int i=0;i<n;i++){\n if(words[i][0] > words[i][1]){\n swap(words[i][0],words[i][1]);\n }\n mp[words[i]]++;\n }\n \n for(auto i : mp)\n count += i.second/2;\n \n return count;\n }\n};\n```
2
0
['C']
2
find-maximum-number-of-string-pairs
||EASY||SIMPLE||JAVA||
easysimplejava-by-himakshikohli-2b46
\n\n# Code\n\nclass Solution {\n public int maximumNumberOfStringPairs(String[] words) {\n int count =0;\n HashMap<String,Integer> arr = new Ha
himakshikohli
NORMAL
2023-07-08T13:15:46.546040+00:00
2023-07-08T13:15:46.546067+00:00
627
false
\n\n# Code\n```\nclass Solution {\n public int maximumNumberOfStringPairs(String[] words) {\n int count =0;\n HashMap<String,Integer> arr = new HashMap<>();\n\n for(int i=0 ;i<words.length;i++){\n String r = new StringBuilder(words[i]).reverse().toString();\n if(arr.containsKey(r)){\n arr.put(r, arr.get(r)+1);\n }\n else{\n arr.put(words[i],0);\n }\n }\n\n for(int j : arr.values()){\n count += j;\n }\n return count;\n }\n}\n```
2
0
['Java']
0
find-maximum-number-of-string-pairs
Most easy c++ ode
most-easy-c-ode-by-ayush07khurana-m0sh
Code\n\nclass Solution \n{\npublic:\n int maximumNumberOfStringPairs(vector<string>& words) {\n int count=0;\n for(int i=0;i<words.size();i++)\
ayush07khurana
NORMAL
2023-06-27T11:20:36.891793+00:00
2023-06-27T11:20:36.891826+00:00
45
false
# Code\n```\nclass Solution \n{\npublic:\n int maximumNumberOfStringPairs(vector<string>& words) {\n int count=0;\n for(int i=0;i<words.size();i++)\n {\n for(int j=i+1;j<words.size();j++)\n {\n string a=words[i];\n string b=words[j];\n reverse(b.begin(),b.end());\n if(a==b)\n {\n count++;\n break;\n }\n }\n }\n return count;\n }\n};\n```
2
0
['Array', 'String', 'C++']
0
find-maximum-number-of-string-pairs
Python3 Solution
python3-solution-by-motaharozzaman1996-6cud
\n\nclass Solution:\n def maximumNumberOfStringPairs(self, words: List[str]) -> int:\n ans = 0\n for i in range(len(words)):\n for j
Motaharozzaman1996
NORMAL
2023-06-25T01:12:29.831282+00:00
2023-06-25T01:12:29.831311+00:00
1,107
false
\n```\nclass Solution:\n def maximumNumberOfStringPairs(self, words: List[str]) -> int:\n ans = 0\n for i in range(len(words)):\n for j in range(i+1, len(words)):\n if words[i][0] == words[j][1] and words[i][1] == words[j][0]:\n ans += 1\n return ans\n```
2
0
['Python', 'Python3']
0
find-maximum-number-of-string-pairs
Easy Bruteforce
easy-bruteforce-by-deveshpatel11-v3oh
\nclass Solution {\n public static int maximumNumberOfStringPairs(String[] words) {\n int ans=0;\n for(int i=0;i<words.length;i++){\n
kanishkpatel1
NORMAL
2023-06-24T16:37:49.077426+00:00
2023-06-24T16:37:49.077445+00:00
1,114
false
```\nclass Solution {\n public static int maximumNumberOfStringPairs(String[] words) {\n int ans=0;\n for(int i=0;i<words.length;i++){\n for(int j=i+1;j<words.length;j++){\n if(words[i].equals(reverse(words[j]))){\n // System.out.println(words[i]);\n ans++;\n }\n }\n }\n return ans;\n }\n public static String reverse(String str) {\n String ans="";\n ans+=str.charAt(1);\n ans+=str.charAt(0);\n return ans;\n }\n}\n```
2
0
['Array', 'Java']
0
find-maximum-number-of-string-pairs
[Python] easy using of set()
python-easy-using-of-set-by-pbelskiy-trqq
During this beweekly contest leetcode server is down again \uD83D\uDE2D\n\npython\nclass Solution:\n def maximumNumberOfStringPairs(self, words: List[str]) -
pbelskiy
NORMAL
2023-06-24T16:00:42.079119+00:00
2023-06-25T08:51:32.221297+00:00
87
false
During this beweekly contest leetcode server is down again \uD83D\uDE2D\n\n```python\nclass Solution:\n def maximumNumberOfStringPairs(self, words: List[str]) -> int:\n v = set()\n \n for i in range(len(words)):\n for j in range(i + 1, len(words)):\n if words[i] == words[j][::-1] and j not in v:\n v.add(j)\n break\n \n return len(v)\n```
2
1
[]
0
find-maximum-number-of-string-pairs
Simple Python Solution
simple-python-solution-by-ascending-3ccb
IntuitionApproachComplexity Time complexity: Space complexity: Code
ascending
NORMAL
2025-04-06T12:49:07.698723+00:00
2025-04-06T12:49:07.698723+00:00
10
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 ```python3 [] class Solution: def maximumNumberOfStringPairs(self, words: List[str]) -> int: used = set() res = 0 for word in words: rev = word[::-1] if rev in used: res += 1 else: used.add(word) return res ```
1
0
['Python3']
0
find-maximum-number-of-string-pairs
Beats 100% C++ Solution, Using Set. T.C = O(n) & S.C = O(n).
beats-100-c-solution-using-set-tc-on-sc-u1aqk
IntuitionUse of Set (Unordered Set)ApproachIterate through the vector from start to finish, checking each element to see if its reverse exists in the set. If th
yugshah7777
NORMAL
2025-04-01T10:57:01.433667+00:00
2025-04-01T10:57:01.433667+00:00
24
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Use of Set (Unordered Set) # Approach <!-- Describe your approach to solving the problem. --> Iterate through the vector from start to finish, checking each element to see if its reverse exists in the set. If the reversed string is found, increment the count without adding the current element to the set. If the reversed string is not found, insert the current element into the set. This approach automatically avoids palindrome elements as there are no duplicate elements in the given vector. # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> O(n) as we are traversing loop just once. Ignoring the T.C. for reversing the String. - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> O(n) in worst case as we are creating a Set and inserting elements into it. # Code ```cpp [] class Solution { public: int maximumNumberOfStringPairs(vector<string>& words) { int count = 0; unordered_set<string> s; for(int i=0; i<words.size(); i++) { string rev = words[i]; reverse(rev.begin(), rev.end()); if(s.find(rev)!=s.end()) count++; else s.insert(words[i]); } return count; } }; ```
1
0
['C++']
0
find-maximum-number-of-string-pairs
EASY TO UNDERSTAND | BEGINNER FRIENDLY | 3ms Runtime | Beats 100% 🥷🏻🔥
easy-to-understand-beginner-friendly-3ms-36nu
IntuitionApproachComplexity Time complexity: Space complexity: Code
tyagideepti9
NORMAL
2025-03-25T17:01:54.937130+00:00
2025-03-25T17:01:54.937130+00:00
54
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 ```csharp [] public class Solution { public int MaximumNumberOfStringPairs(string[] words) { int n = words.Length; int count = 0; for(int i = 0; i < n; i++){ for(int j = i + 1; j < n; j++){ if(words[i][0] == words[j][1] && words[i][1] == words[j][0]){ count++; } } } return count; } } ```
1
0
['Array', 'Hash Table', 'String', 'Simulation', 'Java', 'C#', 'MS SQL Server']
0
find-maximum-number-of-string-pairs
Simple Approach for beginners
simple-approach-for-beginners-by-srinath-rvga
IntuitionApproachComplexity Time complexity: Space complexity: Code
Srinath_Y
NORMAL
2025-02-14T15:08:39.724528+00:00
2025-02-14T15:08:39.724528+00:00
74
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 ```python [] class Solution(object): def maximumNumberOfStringPairs(self, words): count=0 for i in words: for j in range(words.index(i)+1,len(words)): if i[::-1]==words[j]: count+=1 return count ```
1
0
['String', 'Python']
0
find-maximum-number-of-string-pairs
Beginner Friendly | Solution with approach🐐 | 0ms Beats 100%
beginner-friendly-solution-with-approach-7jsy
IntuitionHere we will take use of unordered_set as by doing this we can do this problem in one pass with help of it, else it will take nested loops that's not t
ujjwalBuilds
NORMAL
2025-02-13T19:17:58.093721+00:00
2025-02-13T19:17:58.093721+00:00
79
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> Here we will take use of unordered_set as by doing this we can do this problem in one pass with help of it, else it will take nested loops that's not the perfect approach # Approach <!-- Describe your approach to solving the problem. --> 1. Make an unordered_set & we need to insert element in that `set` cautiously 2. We will use a simple `for loop` for traversing `words` vector 3. Traverse in `words` vector and reverse each element of the `words` vector 4. After that we need to check whether the reversed string already present in `set` or not 5. To check if it exists `s.find(rev)!=s.end()` and this will tell that the searched string already `exists` in the set, So simply we need to do `count++` thus giving us one `string pair`. 6. And if the String is not present in the set then we will simply insert the String in set `s.insert(words)` 7. At last simply return `count` that will tell us maximum number of string pairs # Complexity - Time complexity: O(1) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: int maximumNumberOfStringPairs(vector<string>& words) { int n = words.size(); unordered_set<string> s; int count = 0; for(int i = 0;i<n;i++){ string rev = words[i]; reverse(rev.begin(),rev.end()); if(s.find(rev)!=s.end()) count++; else s.insert(words[i]); } return count; } }; ```
1
0
['C++']
0
find-maximum-number-of-string-pairs
C++ solution using unordered set
c-solution-using-unordered-set-by-k_dadd-yfrp
Intuitionsets consists of unique elementsApproachtraverse on the vector, store the reverse of the element if reversed element is present in set => count++ else
k_daddyyy
NORMAL
2025-02-13T18:46:39.305643+00:00
2025-02-13T18:46:39.305643+00:00
52
false
# Intuition sets consists of unique elements # Approach traverse on the vector, store the reverse of the element if reversed element is present in set => count++ else insert that element into the set # Complexity - Time complexity: $$O(n)$$ - Space complexity: $$O(n)$$ # Code ```cpp [] class Solution { public: int maximumNumberOfStringPairs(vector<string>& words) { int n = words.size(); int count = 0; unordered_set<string> s; for(int i = 0; i < n; i++) { string rev = words[i]; reverse(rev.begin(), rev.end()); if(s.find(rev) != s.end()) count++; else s.insert(words[i]); } return count; } }; ```
1
0
['C++']
0
find-maximum-number-of-string-pairs
best and fast code
best-and-fast-code-by-diptanshu_888-zbaw
IntuitionApproachComplexity Time complexity: Space complexity: Code
diptanshu_888
NORMAL
2025-02-12T19:32:30.705173+00:00
2025-02-12T19:32:30.705173+00:00
98
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 ```java [] class Solution { public int maximumNumberOfStringPairs(String[] words) { HashSet<String> set=new HashSet<>(); int count=0; for(int i=0;i<words.length;i++){ String rev=reverse(words[i]); if(set.contains(rev)){ count++; set.remove(rev);} else set.add(words[i]); } return count; } public String reverse(String s){ StringBuilder sb=new StringBuilder(s); sb.reverse(); return sb.toString(); } } ```
1
0
['Array', 'Hash Table', 'String', 'Simulation', 'Java']
0
find-maximum-number-of-string-pairs
Runtime 2 ms Beats 70.40% Memory 17.55 MB Beats 78.50%
runtime-2-ms-beats-7040-memory-1755-mb-b-0w65
:):Code
ozodbek_bosimov
NORMAL
2025-02-07T12:38:59.824549+00:00
2025-02-07T12:38:59.824549+00:00
73
false
:): # Code ```python3 [] class Solution: def maximumNumberOfStringPairs(self, words: List[str]) -> int: ans = 0 n = len(words) for i in range(n): for j in range(i+1,n): if words[i][::-1] == words[j]: ans +=1 continue return ans ```
1
0
['Python3']
0
find-maximum-number-of-string-pairs
Easy Solution with 100% beats in Java
easy-solution-with-100-beats-in-java-by-i1ilt
The problem is asking us to find the number of pairs of strings in the array words such that one string is the reverse of another. The brute-force approach woul
SANTHOSH_S_AIDS
NORMAL
2025-01-28T08:02:03.559198+00:00
2025-01-28T08:02:03.559198+00:00
166
false
The problem is asking us to find the number of pairs of strings in the array words such that one string is the reverse of another. The brute-force approach would involve checking every string and comparing it with the reversed form of every other string in the list. However, we can optimize this solution. Approach We can use a List<String> (or a Set for better lookup time) to track the words we've seen so far. For each word, we check if its reverse already exists in the list. If it does, we count it as a valid pair. Otherwise, we add the word to the list. This ensures that we're counting each valid pair exactly once. Time Complexity:O(n) O(n) time, and we need to check the reversed string in the list of previously seen words. Space Complexity: O(n) O(n), because we store each word in a list. In the worst case, all words are distinct, so we will store all the words. # Code ```java [] class Solution { public int maximumNumberOfStringPairs(String[] words) { List<String> li =new ArrayList<>(); int count=0; for(int i=0;i<words.length;i++){ StringBuilder sb=new StringBuilder(words[i]); if(li.contains(sb.reverse().toString())){ count++; }else{ li.add(words[i]); } } return count; } } ```
1
0
['Array', 'Java']
1
find-maximum-number-of-string-pairs
simple c++ code 👻
simple-c-code-by-varuntyagig-m52u
Complexity Time complexity: O(n2) Space complexity: O(1) Code
varuntyagig
NORMAL
2025-01-27T09:26:41.174990+00:00
2025-01-27T09:26:41.174990+00:00
63
false
![Screenshot 2025-01-27 at 2.54.58 PM.png](https://assets.leetcode.com/users/images/7cbb411f-cde4-4b5e-af20-5c3310200d57_1737969990.480203.png) # Complexity - Time complexity: $$O(n^2)$$ - Space complexity: $$O(1)$$ # Code ```cpp [] class Solution { public: int maximumNumberOfStringPairs(vector<string>& words) { int count = 0; string str; for (int i = 0; i < words.size(); i++) { for (int j = i + 1; j < words.size(); j++) { str = words[j]; reverse(str.begin(), str.end()); // each string count only once if (words[i] == str) { count += 1; break; } } } return count; } }; ```
1
0
['Array', 'String', 'Counting', 'C++']
0
find-maximum-number-of-string-pairs
Simple C Solution
simple-c-solution-by-mukesh1855-afpz
IntuitionApproach Write a function that takes two strings as paramter to check whether the two strings are palindrome or not. Then pass the two words to the fun
mukesh1855
NORMAL
2025-01-20T16:50:01.555165+00:00
2025-01-20T16:50:01.555165+00:00
22
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach - Write a function that takes two strings as paramter to check whether the two strings are palindrome or not. - Then pass the two words to the function to find the given string is palindrome, if it is palindrome then increase the count by one. <!-- Describe your approach to solving the problem. --> # Code ```c [] int checkpali(char* a,char*b){ int len1 = strlen(a),len2 = strlen(b),i=0; while(i<len1) { if(a[i]!=b[len1-1-i]) return 0; i++; } return 1; } int maximumNumberOfStringPairs(char** words, int size) { int count = 0; for(int i=0;i<size;i++){ for(int j=i+1;j<size;j++) { if(checkpali(words[i],words[j])) count++; } } return count; } ```
1
0
['C']
0
find-maximum-number-of-string-pairs
Count Maximum Reversed String Pairs in an Array
count-maximum-reversed-string-pairs-in-a-5bff
IntuitionTo solve this problem, the main idea is to identify pairs of strings where one is the reverse of the other. Since the words array consists of distinct
aljo00
NORMAL
2025-01-17T04:13:41.534627+00:00
2025-01-17T04:13:41.534627+00:00
52
false
# Intuition To solve this problem, the main idea is to identify pairs of strings where one is the reverse of the other. Since the `words` array consists of distinct strings, we can safely check all possible pairs without worrying about duplicates. The most intuitive approach is to use two nested loops: 1. Fix one string (`words[i]`) and iterate through the rest (`words[j]`) to find a match. 2. Reverse `words[j]` and compare it with `words[i]`. If they match, it means we have found a valid pair. 3. Count such pairs and ensure each string belongs to at most one pair. This approach is straightforward and ensures we cover all possibilities systematically. # Approach 1. **Initialize a Counter**: Start with a `count` variable set to `0`. This will keep track of the number of valid pairs found. 2. **Iterate Through the Array**: - Use a nested loop where the outer loop iterates through each string (`words[i]`), and the inner loop iterates through all subsequent strings (`words[j]`). 3. **Check for Reverse Match**: - For each pair of strings (`words[i]`, `words[j]`), reverse the second string (`words[j]`) using `.split('').reverse().join('')`. - Compare the reversed string with the first string (`words[i]`). If they are equal, it means we have found a valid pair. 4. **Update the Counter**: - If a valid pair is found, increment the `count`. 5. **Return the Result**: - After checking all possible pairs, return the value of `count` as the final result. This approach ensures that all pairs are checked while maintaining clarity and simplicity. Since each string can belong to only one pair, there is no risk of overcounting. # Complexity - **Time Complexity**: The algorithm uses a nested loop to compare each string with all subsequent strings in the array. - Outer loop runs for $$n$$ iterations (where $$n$$ is the length of the array). - Inner loop runs for $$n-1$$, $$n-2$$, ..., 1 iterations for each pass of the outer loop. Therefore, the total number of comparisons is: $$\text{Total comparisons} = 1 + 2 + 3 + ... + (n-1) = \frac{n(n-1)}{2}$$ Hence, the time complexity is $$O(n^2)$$. - **Space Complexity**: - Reversing a string (`words[j].split('').reverse().join('')`) takes $$O(k)$$ space, where $$k$$ is the length of the string (constant in this problem as the length of each word is 2). - Apart from this, no extra space is used, as the operations are done in-place. Therefore, the space complexity is $$O(1)$$. # Code ```javascript [] /** * @param {string[]} words * @return {number} */ var maximumNumberOfStringPairs = function(words) { let count = 0; for (let i = 0; i < words.length; i++) { for (let j = i + 1; j < words.length; j++) { if (words[i] === words[j].split('').reverse().join('')) { count++; } } } return count; }; ```
1
0
['JavaScript']
1
find-maximum-number-of-string-pairs
Simple answer using HashSet
simple-answer-using-hashset-by-saksham_g-4q99
Complexity Time complexity: O(n.m) (n for loop and m for reverse) Space complexity: O(n+m) (n for Set and m for StringBuilder) Code
Saksham_Gupta_
NORMAL
2025-01-03T11:11:53.877446+00:00
2025-01-03T11:11:53.877446+00:00
83
false
<!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: ***O(n.m)*** (n for loop and m for reverse) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: ***O(n+m)*** (n for Set and m for StringBuilder) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public int maximumNumberOfStringPairs(String[] words) { int count = 0; Set<String> set = new HashSet<>(); for(String word: words){ String rev = new StringBuilder(word).reverse().toString(); if(set.contains(rev)){ count++; } set.add(word); } return count; } } ```
1
0
['Array', 'String', 'Java']
0
find-maximum-number-of-string-pairs
Find maximum number of string pairs -Easy solution for beginner -->
find-maximum-number-of-string-pairs-easy-vpu0
Intuition\n\n\n# Approach\nreversing the string and placing it in the words array and checking it with variable a.\n\n# Complexity\n- Time complexity:\n\n\n- Sp
Codeia
NORMAL
2024-08-27T00:55:55.563208+00:00
2024-08-27T00:55:55.563254+00:00
16
false
# Intuition\n\n\n# Approach\nreversing the string and placing it in the words array and checking it with variable a.\n\n# Complexity\n- Time complexity:\n\n\n- Space complexity:\n\n\n# Code\n```cpp []\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(vector<string>& words) {\n int c = 0;\n for(int i = 0;i < words.size(); i++){\n \n string a = words[i];\n\n for(int j = i+1;j < words.size(); j++){\n\n reverse(words[j].begin(),words[j].end());\n\n if(a == words[j]){\n c++;\n }\n }\n }\n return c;\n }\n};\n```
1
0
['C++']
0
find-maximum-number-of-string-pairs
Easy code
easy-code-by-shubhadip_009-g28w
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
Shubhadip_009
NORMAL
2024-08-22T18:22:24.187609+00:00
2024-08-22T18:22:24.187680+00:00
133
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```cpp []\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(vector<string>& words) {\n int n = words.size();\n int count = 0;\n unordered_set<string>s;\n for(int i=0; i<n; i++){\n string rev = words[i];\n reverse(rev.begin(),rev.end());\n if(s.find(rev) != s.end()) count++;\n else s.insert(words[i]);\n }\n return count;\n }\n};\n```
1
0
['C++']
0
find-maximum-number-of-string-pairs
two_loops_check _ki_iska reverse == other elemnt and yes count++
two_loops_check-_ki_iska-reverse-other-e-1npq
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
yesyesem
NORMAL
2024-08-22T17:19:20.272311+00:00
2024-08-22T17:19:20.272336+00:00
40
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```cpp []\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(vector<string>& words) {\n int n=words.size();\n int count=0;\n for(int i=0;i<words.size();i++)\n {\n for(int j=i+1;j<words.size();j++)\n {\n if(i!=j)\n {\n string words2=words[i];\n reverse(words2.begin(),words2.end());\n if(words2==words[j])\n count++;\n\n\n }\n }\n }\n return count;\n \n }\n};\n```
1
0
['C++']
0
find-maximum-number-of-string-pairs
Beats 100%
beats-100-by-manyaagargg-jd0k
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
manyaagargg
NORMAL
2024-07-25T16:34:54.472637+00:00
2024-07-25T16:34:54.472668+00:00
10
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 int maximumNumberOfStringPairs(vector<string>& words) {\n int ans=0;\n for(int i=0; i<words.size(); i++){\n for(int j=i+1; j<words.size(); j++){\n reverse(words[j].begin(), words[j].end());\n if(words[i]==words[j]) ans++;\n }\n }\n return ans;\n }\n};\n```
1
0
['C++']
0
find-maximum-number-of-string-pairs
Easy to Understand || Solution by Navyendhu Menon
easy-to-understand-solution-by-navyendhu-h0wd
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
navyendhummenon
NORMAL
2024-07-08T05:06:16.062519+00:00
2024-07-08T05:06:16.062550+00:00
7
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```\n/**\n * @param {string[]} words\n * @return {number}\n */\nvar maximumNumberOfStringPairs = function(words) {\n\n let count =0\n\n for ( let i=0 ; i<words.length; i++){\n for(let k=i+1 ; k< words.length ; k++){\n if(words[i].split("").reverse().join("")== words[k]){\n count++\n }\n }\n }\n\n return count\n \n};\n```
1
0
['JavaScript']
0
find-maximum-number-of-string-pairs
js solution🔥
js-solution-by-mhdsabeeh-zaby
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
MHDSabeeh
NORMAL
2024-05-04T07:27:49.688968+00:00
2024-05-04T07:27:49.689015+00:00
182
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```\n/**\n * @param {string[]} words\n * @return {number}\n */\nvar maximumNumberOfStringPairs = function(words) {\n let count = 0\n for(let i=0;i<words.length;i++){\n for(let j=i+1;j<words.length;j++){\n if(words[i].split("").reverse().join("") === words[j]){\n count++\n }\n }\n }\n return count\n};\n```
1
0
['JavaScript']
0
find-maximum-number-of-string-pairs
Brute force + O(n) Hashmap solution
brute-force-on-hashmap-solution-by-jaime-ec9h
Brute Force\nSimple brute force method by computing the reverse of every single word and looking ahead the rest of the words to see if any of those match. This
jaimeloeuf
NORMAL
2024-04-11T13:13:19.810671+00:00
2024-04-11T13:13:19.810702+00:00
19
false
### Brute Force\nSimple brute force method by computing the reverse of every single word and looking ahead the rest of the words to see if any of those match. This has a TC of O(n^2) where n is the number of elements in `words`, and a SC of O(1).\n\n```typescript\nfunction maximumNumberOfStringPairs(words: string[]): number {\n let pairs = 0;\n\n for (let i = 0; i < words.length; i++) {\n const reversedWord = words[i].split("").reverse().join("");\n\n for (let j = i + 1; j < words.length; j++) {\n console.log("object", reversedWord, words[j]);\n\n if (words[j] === reversedWord) {\n pairs++;\n break;\n }\n }\n }\n\n return pairs;\n}\n```\n\n### Efficient hashmap solution\nThis is a more efficient solution using a "Hashmap" or Set in this case, so that the loop only run once as we "remember" what was already seen before.\n\nThis has a TC and SC of O(n) where n is the number of elements in `words`.\n\n```typescript\nfunction maximumNumberOfStringPairs(words: string[]): number {\n let pairs = 0;\n const set: Set<string> = new Set();\n\n for (let i = 0; i < words.length; i++) {\n // If the set already contains the current word, it means a pair is found!\n if (set.has(words[i])) {\n pairs++;\n continue;\n }\n\n // Else, reverse the current word and add it to the set\n set.add(words[i].split("").reverse().join(""));\n }\n\n return pairs;\n}\n```
1
0
['Array', 'Hash Table', 'Simulation', 'TypeScript']
0
find-maximum-number-of-string-pairs
Simple java code 1 ms beats 100 % && 41 mb beats 89.25 %
simple-java-code-1-ms-beats-100-41-mb-be-pile
\n# Complexity\n- \n\n# Code\n\nclass Solution {\n public int maximumNumberOfStringPairs(String[] words) {\n int n = words.length;\n int count
Arobh
NORMAL
2024-01-23T04:27:44.701168+00:00
2024-01-23T04:27:44.701187+00:00
4
false
\n# Complexity\n- \n![image.png](https://assets.leetcode.com/users/images/779370d1-dcda-4e8d-b4d9-99e60ad5c61c_1705984027.4342566.png)\n# Code\n```\nclass Solution {\n public int maximumNumberOfStringPairs(String[] words) {\n int n = words.length;\n int count = 0;\n for (int i = 0; i < n; i++) {\n boolean flag = false;\n for (int j = i + 1; j < n; j++) {\n if (check(words[i], words[j])) {\n flag = true;\n break;\n }\n }\n if (flag) {\n count++;\n }\n }\n return count;\n }\n\n private boolean check(String s, String s2) {\n if(s.charAt(0)==s2.charAt(1)&&s.charAt(1)==s2.charAt(0))\n return true;\n return false;\n }\n}\n```
1
0
['Array', 'String', 'Simulation', 'Java']
0
find-maximum-number-of-string-pairs
Simple Solution
simple-solution-by-adhilalikappil-1prs
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
adhilalikappil
NORMAL
2024-01-20T04:53:27.573234+00:00
2024-01-20T04:53:27.573281+00:00
358
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```\n/**\n * @param {string[]} words\n * @return {number}\n */\nvar maximumNumberOfStringPairs = function(words) {\n\n const reverseArr = words.map(x => x.split(\'\').reverse().join(\'\'))\n let count = 0\n\n reverseArr.forEach((x , index)=>{\n for(let i=index+1; i<words.length; i++){\n if(x === words[i]){\n count ++\n }\n }\n })\n \n return count \n\n};\n```
1
0
['JavaScript']
0
find-maximum-number-of-string-pairs
C++ || HashSet
c-hashset-by-luisfrodriguezr-1ing
\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(vector<string>& words) {\n unordered_set<string> hash_set;\n \n int ans = 0;\n for (au
ergodico
NORMAL
2024-01-19T19:44:00.165943+00:00
2024-01-19T19:44:00.165970+00:00
0
false
```\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(vector<string>& words) {\n unordered_set<string> hash_set;\n \n int ans = 0;\n for (auto& word: words) {\n sort(begin(word), end(word));\n if (hash_set.find(word) != end(hash_set) ) {\n hash_set.erase(word);\n ans++;\n } else {\n hash_set.insert(word);\n }\n }\n \n return ans;\n }\n};\n```
1
0
[]
0
find-maximum-number-of-string-pairs
Easy solution || C++
easy-solution-c-by-garimapachori827-iv3y
Code\n\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(vector<string>& words) {\n int count=0;\n for(int i=0;i<words.size();i++){\n
garimapachori827
NORMAL
2023-12-13T16:16:55.983627+00:00
2023-12-13T16:16:55.983662+00:00
92
false
# Code\n```\nclass Solution {\npublic:\n int maximumNumberOfStringPairs(vector<string>& words) {\n int count=0;\n for(int i=0;i<words.size();i++){\n for(int j=i+1;j<words.size();j++){\n if(words[i]==palindrome(words[j])){\n count++;\n }\n }\n }\n\n return count;\n }\n\n string palindrome(string s){\n string st(s.size(), \' \');\n int n=s.size();\n for(int i=0;i<s.size();i++){\n st[i]=s[n-i-1];\n }\n return st;\n }\n\n};\n```
1
0
['Array', 'String', 'C++']
0
find-maximum-number-of-string-pairs
EASY C++ SOLUTION WITH MINIMAL CONCEPTS
easy-c-solution-with-minimal-concepts-by-405g
EASY C++ SOLUTION WITH MINIMAL CONCEPTS\n\n\n# Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to
codermal_
NORMAL
2023-11-08T13:13:52.462054+00:00
2023-11-08T13:13:52.462085+00:00
4
false
**EASY C++ SOLUTION WITH MINIMAL CONCEPTS**\n\n\n# 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 int maximumNumberOfStringPairs(vector<string>& words) {\n int count=0;\n for(int i=0;i<words.size();i++){\n for(int j=i+1;j<words.size();j++){\n string temp=words[j];\n reverse(temp.begin(),temp.end()); // Storing the string array element in temporary string variable and reversing it for checking .\n if(words[i]==temp) count++;\n }\n }\n return count; \n }\n};\n```
1
0
['C++']
0
find-maximum-number-of-string-pairs
Fcuk strrev
fcuk-strrev-by-parthapratimjana99-o9t7
Intuition\n Describe your first thoughts on how to solve this problem. \nstrlen(string_name)\treturns the length of string name.\n2)\tstrcpy(destination, source
parthapratimjana99
NORMAL
2023-10-08T07:52:45.214225+00:00
2023-10-08T07:52:45.214247+00:00
299
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nstrlen(string_name)\treturns the length of string name.\n2)\tstrcpy(destination, source)\tcopies the contents of source string to destination string.\n3)\tstrcat(first_string, second_string)\tconcats or joins first string with second string. The result of the string is stored in first string.\n4)\tstrcmp(first_string, second_string)\tcompares the first string with second string. If both strings are same, it returns 0.\n5)\tstrrev(string)\treturns reverse string.\n6)\tstrlwr(string)\treturns string characters in lowercase.\n![pexels-aleksandar-pasaric-3629227.jpg](https://assets.leetcode.com/users/images/a7ee3882-d120-4642-9acf-45dad42756ac_1696751561.2471952.jpeg)\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```\nvoid stringev(char *str1)\n{ \n // declare variable \n int i, len, temp; \n len = strlen(str1); // use strlen() to get the length of str string \n \n // use for loop to iterate the string \n for (i = 0; i < len/2; i++) \n { \n // temp variable use to temporary hold the string \n temp = str1[i]; \n str1[i] = str1[len - i - 1]; \n str1[len - i - 1] = temp; \n } \n \n}\n \nint maximumNumberOfStringPairs(char ** words, int wordsSize){\n int ho=0;\n \n for(int i=0;i<wordsSize;i++){\n stringev(words[i]);\n for(int j=i+1;j<wordsSize;j++)\n if(!strcmp(words[i],words[j])){\n ho++;\n }\n}\nreturn ho;\n}\n\n\n\n```
1
0
['C']
1
find-maximum-number-of-string-pairs
JAVA SOLUTION || 100% FASTER || 1MS SOLUTION
java-solution-100-faster-1ms-solution-by-8wk9
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
viper_01
NORMAL
2023-09-06T11:40:05.971361+00:00
2023-09-06T11:40:05.971382+00:00
5
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 {\n public int maximumNumberOfStringPairs(String[] words) {\n boolean[] flag = new boolean[words.length];\n\n int ans = 0;\n\n for(int i = 0; i < words.length - 1; i++) {\n String word1 = words[i];\n\n for(int j = i + 1; j < words.length; j++){\n if(flag[j])\n continue;\n\n String word2 = words[j];\n\n if(word1.charAt(0) == word2.charAt(1) && word1.charAt(1) == word2.charAt(0)){\n flag[i] = true;\n flag[j] = true;\n ans++;\n }\n }\n }\n\n return ans;\n }\n}\n```
1
0
['Java']
0
find-maximum-number-of-string-pairs
Beats 95.59% / 64.74%. The most simple js solution
beats-9559-6474-the-most-simple-js-solut-z9v0
\nvar maximumNumberOfStringPairs = function(words) {\n const set = new Set()\n let cnt = 0\n \n for (let word of words) {\n if (set.has(word.
tishka
NORMAL
2023-08-23T11:31:42.213235+00:00
2023-08-23T11:31:42.213262+00:00
80
false
```\nvar maximumNumberOfStringPairs = function(words) {\n const set = new Set()\n let cnt = 0\n \n for (let word of words) {\n if (set.has(word.split(\'\').reverse().join(\'\'))) cnt++\n \n set.add(word)\n }\n \n return cnt\n};\n```
1
0
['JavaScript']
1
find-maximum-number-of-string-pairs
Rust/Python Linear time/space with explanation
rustpython-linear-timespace-with-explana-iz8u
Intuition\nStore the counts of all strings in the hashmap. Now iterate over all our strings and find their reversed strings. Check if it exists in a hashmap. \n
salvadordali
NORMAL
2023-07-25T23:40:58.759144+00:00
2023-07-25T23:40:58.759192+00:00
45
false
# Intuition\nStore the counts of all strings in the hashmap. Now iterate over all our strings and find their reversed strings. Check if it exists in a hashmap. \n\nNow we have two possible options:\n - reverse string is equal to our original string. To be able to find a reverse we need to have at least two values in a counter `map[rev] >= 2`. If this is the case, increment the results and decrease counter by 2\n - otherwise to be able to find a reverse, you need to have at least one value in a counter. In this case also increment the result and decrease counter by 1.\n\n# Complexity\n- Time complexity: $O(n)$\n- Space complexity: $O(n)$\n\n# Code\n\n```Rust []\nuse std::collections::HashMap;\n\nimpl Solution {\n pub fn maximum_number_of_string_pairs(arr: Vec<String>) -> i32 {\n let mut map: HashMap<String, i32> = HashMap::new();\n for v in &arr {\n *map.entry(v.to_string()).or_default() += 1;\n }\n\n let mut res = 0;\n for v in arr {\n let v_rev: String = v.chars().rev().collect();\n if !map.contains_key(&v_rev) {\n continue;\n }\n if v == v_rev {\n if *map.get(&v_rev).unwrap() > 1 {\n res += 1;\n *map.entry(v_rev.to_string()).or_default() -= 2;\n }\n } else {\n if *map.get(&v_rev).unwrap() > 0 {\n res += 1;\n *map.entry(v_rev.to_string()).or_default() -= 1;\n }\n }\n }\n\n return res / 2;\n }\n}\n```\n```python []\nfrom collections import Counter\n\nclass Solution:\n def maximumNumberOfStringPairs(self, words: List[str]) -> int:\n cnt, res = Counter(words), 0\n for v in words:\n v_rev = v[::-1]\n if v == v_rev:\n if cnt[v] >= 2:\n res += 1\n cnt[v] -= 2\n else:\n if cnt[v_rev] >= 1:\n res += 1;\n cnt[v_rev] -= 1\n \n return res // 2\n```\n
1
0
['Python3', 'Rust']
0
find-maximum-number-of-string-pairs
Java Easy to Understand Solution Using HashSet
java-easy-to-understand-solution-using-h-3iph
Code\n\nclass Solution {\n public int maximumNumberOfStringPairs(String[] words) {\n int count = 0;\n\t\tSet<String> ans = new HashSet<>();\n\t\tfor (
brothercode
NORMAL
2023-07-22T17:58:28.183301+00:00
2023-07-22T18:01:50.860433+00:00
5
false
# Code\n```\nclass Solution {\n public int maximumNumberOfStringPairs(String[] words) {\n int count = 0;\n\t\tSet<String> ans = new HashSet<>();\n\t\tfor (String str : words) {\n\t\t\tchar ch[] = str.toCharArray();\n\t\t\tArrays.sort(ch); // Sort the Characters of each string.\n\t\t\tif (!ans.add(String.valueOf(ch))) // If the duplicate exists while adding in the set, increase the count.\n\t\t\t\tcount++;\n\t\t}\n\t\treturn count;\n }\n}\n```\n\nPlease upvote, if you like this. Thanks.
1
0
['Java']
0
find-maximum-number-of-string-pairs
[JAVA] easy solution without StringBuilder/Map
java-easy-solution-without-stringbuilder-y18x
Intuition\n Describe your first thoughts on how to solve this problem. \nIn the entire array words count the number of times a word and its reverse is present i
Jugantar2020
NORMAL
2023-07-18T18:03:41.907219+00:00
2023-07-18T18:03:41.907244+00:00
370
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nIn the entire array words count the number of times a word and its reverse is present in the array\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nfor all the words check if the first letter of a word equals the second letter of another word in the array `words` and vice versa\n\n# Complexity\n- Time complexity: O(n * 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 {\n public int maximumNumberOfStringPairs(String[] words) {\n int ans = 0;\n for (int i = 0; i < words.length; i ++) {\n for(int j = i + 1; j < words.length; j ++) \n if(words[i].charAt(0) == words[j].charAt(1) && words[i].charAt(1) == words[j].charAt(0))\n ans ++;\n } \n return ans;\n }\n}\n```
1
0
['Array', 'String', 'Simulation', 'Java']
1
find-maximum-number-of-string-pairs
Kotlin 1 line
kotlin-1-line-by-georgcantor-iwp8
\nfun maximumNumberOfStringPairs(a: Array<String>) = a.groupingBy { it.toSortedSet() }.eachCount().count { it.value > 1 }\n
GeorgCantor
NORMAL
2023-07-16T10:58:51.919407+00:00
2023-07-16T12:19:55.416481+00:00
9
false
```\nfun maximumNumberOfStringPairs(a: Array<String>) = a.groupingBy { it.toSortedSet() }.eachCount().count { it.value > 1 }\n```
1
0
['Kotlin']
0
find-maximum-number-of-string-pairs
One line solution
one-line-solution-by-likils-gaul
Code\n\nclass Solution {\n func maximumNumberOfStringPairs(_ words: [String]) -> Int {\n return words.count - Set(words.map(Set.init)).count\n }\n}
likils
NORMAL
2023-07-14T07:55:08.488844+00:00
2023-07-14T07:55:08.488870+00:00
38
false
# Code\n```\nclass Solution {\n func maximumNumberOfStringPairs(_ words: [String]) -> Int {\n return words.count - Set(words.map(Set.init)).count\n }\n}\n```
1
0
['Swift']
1
find-maximum-number-of-string-pairs
Simple PHP solution
simple-php-solution-by-vlados117-ycah
Complexity\n- Time complexity: O(n)\n Add your time complexity here, e.g. O(n) \n\n\n# Code\n\nclass Solution {\n\n /**\n * @param String[] $words\n
Vlados117
NORMAL
2023-07-14T07:47:08.622600+00:00
2023-07-14T07:51:12.011558+00:00
15
false
# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```\nclass Solution {\n\n /**\n * @param String[] $words\n * @return Integer\n */\n function maximumNumberOfStringPairs($words) {\n //Here we\'ll keep words as array keys\n $hash = [];\n $counter = 0;\n //for every item in $words\n foreach ($words as $value) {\n //if $hash has item with key == reverse $value then increment $counter\n if ($hash[strrev($value)]) {\n $counter++;\n } else {\n //if item has not pair then just save it in $hash\n $hash[$value] = \'1\';\n }\n }\n return $counter;\n }\n}\n```\n# P.S.\nUpvote if it helps you)\n
1
0
['PHP']
0
find-maximum-number-of-string-pairs
Java || Simple Solution ✅ || Rutime - 100% 💥 || Memory - 94% 💥 || With Explanation ✅
java-simple-solution-rutime-100-memory-9-ljni
Approach\n\n1. Initialize two variables: n to store the length of the words array and cnt to keep track of the count of valid pairs.\n2. Use nested loops to ite
akobirswe
NORMAL
2023-07-11T05:34:29.553852+00:00
2023-07-11T05:34:29.553869+00:00
379
false
# Approach\n\n1. Initialize two variables: `n` to store the length of the `words` array and `cnt` to keep track of the count of valid pairs.\n2. Use nested loops to iterate over all possible pairs of strings in the `words` array. The outer loop variable `i` represents the index of the first word, and the inner loop variable `j` represents the index of the second word.\n3. Inside the nested loops, check if the first character of `words[i]` is equal to the second character of `words[j]`, and the second character of `words[i]` is equal to the first character of `words[j]`. This condition ensures that the two words can be paired according to the given conditions.\n4. If the condition is satisfied, increment the `cnt` variable by 1.\n5. After the loops finish executing, return the final value of `cnt` as the maximum number of pairs that can be formed.\n\n\n# Complexity\n- Time complexity: $$O(n^2)$$\n\n- Space complexity: $$O(1)$$\n\n# Code\n```\nclass Solution {\n public int maximumNumberOfStringPairs(String[] words) {\n int n = words.length;\n int cnt = 0;\n\n for(int i = 0; i < n; i++)\n for(int j = i + 1; j < n; j++)\n if(words[i].charAt(0) == words[j].charAt(1) && words[i].charAt(1) == words[j].charAt(0))\n cnt++;\n \n return cnt;\n }\n}\n```
1
0
['Array', 'String', 'Simulation', 'Java', 'C#']
0
find-maximum-number-of-string-pairs
C++ | Easy Solution Using Unordered Set
c-easy-solution-using-unordered-set-by-s-tx4j
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# Co
shweta0098
NORMAL
2023-07-08T10:15:40.599402+00:00
2023-07-08T10:15:40.599428+00:00
17
false
# 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 {\npublic:\n int maximumNumberOfStringPairs(vector<string>& words) {\n unordered_set<string> s;\n int maxPair = 0;\n for(string word : words)\n {\n if(s.find(word) != s.end())\n {\n maxPair++;\n }\n else\n {\n reverse(word.begin(),word.end());\n s.insert(word);\n }\n }\n return maxPair;\n }\n};\n```
1
0
['Hash Table', 'C++']
0
find-maximum-number-of-string-pairs
✅👌JAVA | 2 DIFFERENT APPROACH | EASY
java-2-different-approach-easy-by-dipesh-d691
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
dipesh_12
NORMAL
2023-07-07T14:46:33.593289+00:00
2023-07-07T14:46:33.593317+00:00
703
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 {\n public int maximumNumberOfStringPairs(String[] words) {\n HashSet<String>set=new HashSet<>();\n for(String s:words){\n set.add(s);\n }\n System.out.println(set);\n\n int count=0;\n for(int i=0;i<words.length;i++){\n String rev=reverse(words[i]);\n set.remove(words[i]);\n if(set.contains(rev)){\n count++;\n set.remove(rev);\n \n }\n }\n return count;\n }\n\n public String reverse(String temp){\n char ch[]=temp.toCharArray();\n char cur=ch[0];\n ch[0]=ch[1];\n ch[1]=cur;\n String ans="";\n for(int i=0;i<ch.length;i++){\n ans+=ch[i];\n }\n\n return ans;\n }\n}\n```
1
0
['Java']
0
find-maximum-number-of-string-pairs
📌Solution with shift() method
solution-with-shift-method-by-m3f-smq1
Intuition\n Describe your first thoughts on how to solve this problem. \n1. Remove the first item from the array words and returns that removed item;\n2. Reverc
M3f
NORMAL
2023-06-29T11:34:53.198083+00:00
2023-06-29T11:34:53.198112+00:00
235
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n1. Remove the first `item` from the array `words` and returns that removed `item`;\n2. Reverce letters in removed `item`;\n3. Determine whether the array `words` includes a reverce `item` among its entries;\n4. Repeat until the array `words` has elements.\n\n# Code\n```\n/**\n * @param {string[]} words\n * @return {number}\n */\nconst maximumNumberOfStringPairs = (words) => {\n let num = 0;\n while (words.length) {\n let item = words.shift();\n item = item[1] + item[0];\n if (words.includes(item)) num++;\n }\n return num;\n}\n```
1
0
['JavaScript']
0
find-maximum-number-of-string-pairs
[scala] - make pairs by indices, count
scala-make-pairs-by-indices-count-by-nik-2mwk
Code\n\nobject Solution {\n def maximumNumberOfStringPairs(words: Array[String]): Int = {\n val counts =\n words.indices.map { i =>\n val revers
nikiforo
NORMAL
2023-06-29T09:18:06.001054+00:00
2023-06-29T09:18:06.001087+00:00
16
false
# Code\n```\nobject Solution {\n def maximumNumberOfStringPairs(words: Array[String]): Int = {\n val counts =\n words.indices.map { i =>\n val reversed = words(i).reverse\n words.iterator.drop(i + 1).count(_ == reversed)\n }\n counts.sum\n }\n}\n```
1
0
['Scala']
0
find-maximum-number-of-string-pairs
JAVA | HashSet
java-hashset-by-sourin_bruh-k6iq
Solution:\n\nclass Solution {\n public int maximumNumberOfStringPairs(String[] words) {\n Set<String> set = new HashSet<>();\n int cnt = 0;\n
sourin_bruh
NORMAL
2023-06-28T13:30:00.172784+00:00
2023-06-28T13:30:00.172818+00:00
223
false
# Solution:\n```\nclass Solution {\n public int maximumNumberOfStringPairs(String[] words) {\n Set<String> set = new HashSet<>();\n int cnt = 0;\n for (String s : words) {\n StringBuilder sb = new StringBuilder(s).reverse();\n if (set.contains(sb.toString())) {\n cnt++;\n } else {\n set.add(s);\n }\n }\n return cnt;\n }\n}\n```\n### Time complexity: $$O(n^2)$$\n> Worst case time complexity for lookup in hashset can be $$O(n)$$.\n### Space complexity: $$O(n)$$
1
0
['Array', 'Hash Table', 'String', 'Java']
0