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
lexicographically-smallest-palindrome
Lexicographically Smallest Palindrome Solution in C++
lexicographically-smallest-palindrome-so-27li
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
The_Kunal_Singh
NORMAL
2023-05-26T04:08:09.611109+00:00
2023-05-26T04:08:09.611135+00:00
63
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)$$ -->\nO(n)\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\nO(1)\n# Code\n```\nclass Solution {\npublic:\n string makeSmallestPalindrome(string s) {\n int i;\n for(i=0 ; i<s.length()/2 ; i++)\n {\n if(s[i]>s[s.length()-1-i])\n {\n s[i] = s[s.length()-1-i];\n }\n else\n {\n s[s.length()-1-i] = s[i];\n }\n }\n return s;\n }\n};\n```\n![upvote new.jpg](https://assets.leetcode.com/users/images/69d30596-e4ec-4fc8-9dfd-f6573383ffd5_1685074084.2205186.jpeg)\n
2
0
['C++']
0
lexicographically-smallest-palindrome
Easy Solution in Java | 8 ms - 100% beats | Fully Explained
easy-solution-in-java-8-ms-100-beats-ful-xgrl
\n\n# Approach\n\nTo solve the problem, we follow these steps:\n\n1. Convert the input string s into a character array arr for easy manipulation.\n2. Determine
akobirswe
NORMAL
2023-05-23T16:02:42.630730+00:00
2023-07-03T20:32:26.659192+00:00
164
false
\n\n# Approach\n\nTo solve the problem, we follow these steps:\n\n1. Convert the input string `s` into a character array `arr` for easy manipulation.\n2. Determine the length of the array and store it in the variable `n`.\n3. Iterate over the array from the beginning (`i = 0`) to the middle (`i < n / 2`).\n4. Check if the characters at positions `i` and `j` (where `j = n - 1 - i`) are different.\n5. If the characters are different, replace both characters with the lexicographically smaller one.\n6. Finally, convert the modified character array `arr` back into a string and return it as the result.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(n)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public String makeSmallestPalindrome(String s) {\n char[] arr = s.toCharArray();\n int n = arr.length;\n for(int i = 0, j = n - 1; i < n / 2; i++, j--)\n if(arr[i] != arr[j]){\n char smallOne = (char) Math.min(arr[i], arr[j]);\n arr[i] = arr[j] = smallOne;\n }\n return new String(arr);\n }\n}\n```
2
0
['Array', 'Two Pointers', 'String', 'Java']
0
lexicographically-smallest-palindrome
[JavaScript] 2697. Lexicographically Smallest Palindrome
javascript-2697-lexicographically-smalle-feb1
---\n\nWeekly Contest 346 solutions:\n- Q1 - https://leetcode.com/problems/minimum-string-length-after-removing-substrings/solutions/3547566/javascript-2696-min
pgmreddy
NORMAL
2023-05-21T06:43:02.488269+00:00
2023-05-21T06:47:26.528402+00:00
675
false
---\n\nWeekly Contest 346 solutions:\n- Q1 - https://leetcode.com/problems/minimum-string-length-after-removing-substrings/solutions/3547566/javascript-2696-minimum-string-length-after-removing-substrings/\n- Q2 - https://leetcode.com/problems/lexicographically-smallest-palindrome/solutions/3547563/javascript-2697-lexicographically-smallest-palindrome/\n- Q3 - https://leetcode.com/problems/find-the-punishment-number-of-an-integer/solutions/3547553/javascript-2698-find-the-punishment-number-of-an-integer/\n\n---\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```\nconst makeSmallestPalindrome = function (s) {\n const n = s.length\n s = s.split(\'\')\n const halfN = Math.trunc(n / 2)\n for (let i = 0; i < halfN; i++) {\n if (s[i] !== s[n - 1 - i]) {\n if (s[i] < s[n - 1 - i]) {\n s[n - 1 - i] = s[i]\n } else {\n s[i] = s[n - 1 - i]\n }\n }\n }\n return s.join(\'\')\n}\n\n```
2
0
['JavaScript']
0
lexicographically-smallest-palindrome
Easily understandable C++ solution
easily-understandable-c-solution-by-heal-x56p
Intuition\nJust try to make the (i)th and (l-1-i)th characters same with the given condition (The lower value charater shoulb be taken) #where l is the length o
Healthy_UG_007
NORMAL
2023-05-21T05:58:34.036638+00:00
2023-05-21T05:58:34.036663+00:00
73
false
# Intuition\nJust try to make the (i)th and (l-1-i)th characters same with the given condition (The lower value charater shoulb be taken) #where l is the length of th string\n\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\nUse a for loop and iterate upto the middle and try to make the characters same with the given condition\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string makeSmallestPalindrome(string s) {\n int l=s.length();\n for(int i=0;i<l/2;i++){\n if(s[i]!=s[l-1-i]){\n if(s[i]<s[l-1-i]){ //checking the ascii values of the \n // characters then making them same\n s[l-1-i]=s[i];\n }\n else{\n s[i]=s[l-1-i];\n }\n }\n }\n return s;\n }\n};\n```
2
0
['String', 'C++']
0
lexicographically-smallest-palindrome
| | ✅ Very Simple C++ Solution with 100% Time and Space Complexity ✅ | |
very-simple-c-solution-with-100-time-and-bmb4
Intuition\nPlease UPVOTE if you LIKE the Solution and COMMENT your own Code and thoughts.\n\n# Approach\nThese Type of Questions are Solved using Two pointers,\
Satyam_Singh_Nijwala
NORMAL
2023-05-21T05:04:04.605848+00:00
2023-05-21T05:04:04.605887+00:00
218
false
# Intuition\nPlease UPVOTE if you LIKE the Solution and COMMENT your own Code and thoughts.\n\n# Approach\nThese Type of Questions are Solved using Two pointers,\nOne from Starting index i=0 and other from end r=size of string -1.\n\n# Complexity\n- Time complexity:\n100%\n\n- Space complexity:\n100%\n\n# Code\n```\nclass Solution {\npublic:\n string makeSmallestPalindrome(string s) {\n int i=0,r=s.size()-1;\n while(i<r)\n {\n if(s[i]!=s[r])\n {\n s[i]=s[r]=(s[i]<s[r])?s[i]:s[r];\n }\n i++;\n r--;\n }\n return s;\n }\n};\n```
2
0
['C++']
0
lexicographically-smallest-palindrome
Easiest 2 Pointers Approach | Short code explained
easiest-2-pointers-approach-short-code-e-i3wj
Intuition\nWe need to make the string palindrome. Thus we need to compare first and last indices.\n\n# Approach\n- (step 1) Keep one index at beginning of strin
Jeetaksh
NORMAL
2023-05-21T04:40:26.862455+00:00
2023-05-21T04:40:26.862489+00:00
122
false
# Intuition\nWe need to make the string palindrome. Thus we need to compare first and last indices.\n\n# Approach\n- **(step 1)** Keep one index at beginning of string and other at the end.\n- **(case 1)** Update the first index to the character at last index if last index character is alphabetically smaller.\n- **(case 2)** Else update last index character to first index character.\n- **(step 3)** Increment and decrement the first and last indexes.\n\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string makeSmallestPalindrome(string s) {\n int i=0, int j=s.size()-1; //Step 1\n while(i<j){\n if(s[i]<=s[j]) s[j]=s[i]; //Case 1\n else s[i]=s[j]; //Case 2\n i++,j--; //Step 3\n }\n return s;\n }\n};\n```\n**Please upvote if it helped. Happy Coding!**
2
0
['C++']
0
lexicographically-smallest-palindrome
Simplest of all solution | Super easy to understand
simplest-of-all-solution-super-easy-to-u-5vw8
Just compare front and back letters.\n- If they are not equal then replace the larger letter with the smaller one.\n\n# Code\n\nclass Solution:\n def makeSma
younus-Sid
NORMAL
2023-05-21T04:27:30.747284+00:00
2023-05-21T04:27:30.747320+00:00
659
false
- Just compare front and back letters.\n- If they are not equal then replace the larger letter with the smaller one.\n\n# Code\n```\nclass Solution:\n def makeSmallestPalindrome(self, s: str) -> str:\n for i in range(int(len(s)/2)):\n if s[i] != s[len(s)-i-1]:\n if s[i] < s[len(s)-i-1]:\n s = s[:len(s)-i-1] + s[i] + s[len(s)-i:]\n else:\n s = s[:i] + s[len(s)-i-1] + s[i+1:]\n return s\n```
2
0
['Python3']
0
lexicographically-smallest-palindrome
C++ || Easiest 4 lines of code
c-easiest-4-lines-of-code-by-mrigank_200-tjom
Here is my c++ code for this problem.\n\n# Complexity\n- Time complexity:O(n/2)\n\n- Space complexity:O(1)\n\n# Code\n\nclass Solution {\npublic:\n string ma
mrigank_2003
NORMAL
2023-05-21T04:25:23.190296+00:00
2023-05-21T04:25:23.190336+00:00
540
false
Here is my c++ code for this problem.\n\n# Complexity\n- Time complexity:$$O(n/2)$$\n\n- Space complexity:$$O(1)$$\n\n# Code\n```\nclass Solution {\npublic:\n string makeSmallestPalindrome(string s) {\n for(int i=0; i<s.size()/2; i++){\n if(s[i]!=s[s.size()-1-i]){\n (s[i]<s[s.size()-1-i])?s[s.size()-1-i]=s[i]:s[i]=s[s.size()-1-i];\n }\n }\n return s;\n }\n};\n```
2
0
['String', 'C++']
1
lexicographically-smallest-palindrome
EASIEST JAVA SOLUTION EVER
easiest-java-solution-ever-by-nikhil_rat-s9kv
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
nikhil_rathi93
NORMAL
2023-05-21T04:15:31.398198+00:00
2023-05-21T04:18:37.737871+00:00
553
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 String makeSmallestPalindrome(String s) {\n char[] arr = s.toCharArray();\n int n = arr.length;\n\n for (int i = 0; i < n / 2; i++) {\n int j = n - i - 1;\n if (arr[i] != arr[j]) {\n arr[j] = arr[i] < arr[j] ? arr[i] : arr[j];\n arr[i] = arr[j];\n }\n }\n\n return new String(arr);\n }\n}\n```\n`**UPVOTE PLEASE**``\n```
2
0
['C++', 'Java']
0
lexicographically-smallest-palindrome
JAVA Easy SOlution || 100 Faster
java-easy-solution-100-faster-by-mayur01-v5k7
\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n\nclass Solution {\n public String makeSmallestPalindrome(String s) {\n \n char []ch=s.toC
mayur0106
NORMAL
2023-05-21T04:06:34.981335+00:00
2023-05-21T04:06:34.981366+00:00
280
false
\n- Time complexity: O(n)\n\n- Space complexity: O(n)\n\n```\nclass Solution {\n public String makeSmallestPalindrome(String s) {\n \n char []ch=s.toCharArray();\n \n int i=0;\n int j=s.length()-1;\n while(i<=j)\n {\n if(ch[i]<ch[j])ch[j]=ch[i];\n else if(ch[i]>ch[j])ch[i]=ch[j];\n i++;\n j--;\n }\n StringBuilder S=new StringBuilder();\n for(char c:ch) S.append(c);\n \n return S.toString();\n }\n}\n```
2
0
['Java']
0
lexicographically-smallest-palindrome
EASY SOLUTION USING LOOPS || BRUTE FORCE BEATING 100% || C++ & JAVA SOLUTION
easy-solution-using-loops-brute-force-be-mk6z
IntuitionTo convert the given string into a palindrome with the minimum number of operations, we need to ensure that the string reads the same forward and backw
arshi_bansal
NORMAL
2025-03-15T10:11:40.223170+00:00
2025-03-15T10:11:40.223170+00:00
93
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> To convert the given string into a palindrome with the minimum number of operations, we need to ensure that the string reads the same forward and backward. For each character s[i] in the first half, it should match its corresponding character s[n-i-1] in the second half. If they are different, we must replace one of them. To ensure lexicographically smallest palindrome, we always choose the smaller character when making replacements. # Approach <!-- Describe your approach to solving the problem. --> 1. **Two Pointers:** Use one pointer at the left (i) and another at the right (n-i-1). 2. **Replace Characters:** - If s[i] != s[n-i-1], replace the larger one with the smaller one. - This guarantees minimal changes and maintains lexicographical order. 3. **Continue Until Middle:** Process characters until the middle of the string is reached. # Complexity - Time complexity: O(n) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(n) <!-- Add your space complexity here, e.g. $$O(n)$$ --> **IN JAVA** ![image.png](https://assets.leetcode.com/users/images/272546ef-6945-4057-9d7f-12e09921e427_1742033319.0282185.png) **IN C++** ![image.png](https://assets.leetcode.com/users/images/91482789-c5a7-4ba8-91ff-479fc89fb485_1742033434.4294922.png) # Code ```JAVA [] class Solution { public String makeSmallestPalindrome(String s) { char[] chars=s.toCharArray(); int n=chars.length; for (int i = 0; i < n / 2; i++) { int j = n - i - 1; if (chars[i] != chars[j]) { chars[i] = chars[j] = (char) Math.min(chars[i], chars[j]); } } return new String(chars); } } ``` ```CPP [] class Solution { public: string makeSmallestPalindrome(string s) { int n = s.size(); for (int i = 0; i < n / 2; i++) { int j = n - i - 1; if (s[i] != s[j]) { s[i] = s[j] = min(s[i], s[j]); } } return s; } }; ```
1
0
['Two Pointers', 'String', 'Greedy', 'C++', 'Java']
0
lexicographically-smallest-palindrome
☑️ Golang solution
golang-solution-by-codemonkey80s-jl5v
Code
CodeMonkey80s
NORMAL
2025-01-28T00:25:41.604377+00:00
2025-01-28T00:25:41.604377+00:00
34
false
# Code ```golang [] func makeSmallestPalindrome(s string) string { output := []byte(s) for i, j := 0, len(s)-1; i <= j; i, j = i+1, j-1 { if s[i] == s[j] { continue } output[i] = min(s[i], s[j]) output[j] = output[i] } return string(output) } ```
1
0
['Go']
0
lexicographically-smallest-palindrome
Легчайшая
legchaishaia-by-danisdeveloper-zpte
Code
DanisDeveloper
NORMAL
2025-01-03T11:18:39.656020+00:00
2025-01-03T11:18:39.656020+00:00
45
false
# Code ```cpp [] class Solution { public: string makeSmallestPalindrome(string s) { int n = s.length(); for(int i=0;i<n/2;++i){ char* left = &s[i]; char* right = &s[n - i - 1]; char diff = *right - *left; if(diff == 0) continue; if(diff > 0) *right = *left; else *left = *right; } return s; } }; ```
1
0
['C++']
0
lexicographically-smallest-palindrome
Two pointers, in place.
two-pointers-in-place-by-michelusa-w6un
As we are ask for a palindrome, it is intuitive to track from both: start of string and end of string Because we are asked for minimum, apply minimum character
michelusa
NORMAL
2024-12-29T23:56:14.704999+00:00
2024-12-29T23:56:14.704999+00:00
105
false
As we are ask for a palindrome, it is intuitive to track from both: * start of string * and end of string Because we are asked for minimum, apply minimum character if the two compared elements are different. O(N) # Code ```cpp [] class Solution { public: string makeSmallestPalindrome(string s) { for (size_t l = 0, r = s.size() - 1; l < r; ++l, --r) { if (s[l] != s[r]) { s[l] = s[r] = std::min(s[l], s[r]); } } return s; } }; ```
1
0
['Two Pointers', 'C++']
0
lexicographically-smallest-palindrome
Python Simple Code
python-simple-code-by-nagaraj08-4fxu
\n# Code\n\nclass Solution(object):\n def makeSmallestPalindrome(self, s):\n """\n :type s: str\n :rtype: str\n """\n i =
NAGARAJ08
NORMAL
2024-08-11T07:25:43.264159+00:00
2024-08-11T07:25:43.264188+00:00
263
false
\n# Code\n```\nclass Solution(object):\n def makeSmallestPalindrome(self, s):\n """\n :type s: str\n :rtype: str\n """\n i = 0\n j = len(s)-1\n\n s = list(s)\n while i <j:\n\n if s[i]!=s[j]:\n if s[i]<s[j]:\n s[j] = s[i]\n elif s[i]>s[j]:\n s[i] = s[j]\n i+=1\n j-=1\n\n return \'\'.join(s)\n\n```
1
0
['Python']
0
lexicographically-smallest-palindrome
Java | JavaScript | TypeScript | C++ | C# | Kotlin | Go Solution.
java-javascript-typescript-c-c-kotlin-go-o1va
Java []\npublic class Solution {\n\n public String makeSmallestPalindrome(String s) {\n char[] lexicographicallySmallestPalindrome = s.toCharArray();\
LachezarTsK
NORMAL
2024-07-15T16:32:12.168156+00:00
2024-07-15T16:37:25.007147+00:00
63
false
```Java []\npublic class Solution {\n\n public String makeSmallestPalindrome(String s) {\n char[] lexicographicallySmallestPalindrome = s.toCharArray();\n int left = 0;\n int right = lexicographicallySmallestPalindrome.length - 1;\n\n while (left < right) {\n if (lexicographicallySmallestPalindrome[left] < lexicographicallySmallestPalindrome[right]) {\n lexicographicallySmallestPalindrome[right] = lexicographicallySmallestPalindrome[left];\n } else {\n lexicographicallySmallestPalindrome[left] = lexicographicallySmallestPalindrome[right];\n }\n ++left;\n --right;\n }\n return String.valueOf(lexicographicallySmallestPalindrome);\n }\n}\n```\n```JavaScript []\n/**\n * @param {string} s\n * @return {string}\n */\nvar makeSmallestPalindrome = function (s) {\n const lexicographicallySmallestPalindrome = s.split(\'\');\n let left = 0;\n let right = lexicographicallySmallestPalindrome.length - 1;\n\n while (left < right) {\n if (lexicographicallySmallestPalindrome[left] < lexicographicallySmallestPalindrome[right]) {\n lexicographicallySmallestPalindrome[right] = lexicographicallySmallestPalindrome[left];\n } else {\n lexicographicallySmallestPalindrome[left] = lexicographicallySmallestPalindrome[right];\n }\n ++left;\n --right;\n }\n return lexicographicallySmallestPalindrome.join(\'\');\n};\n```\n```TypeScript []\nfunction makeSmallestPalindrome(s: string): string {\n const lexicographicallySmallestPalindrome: string[] = s.split(\'\');\n let left = 0;\n let right = lexicographicallySmallestPalindrome.length - 1;\n\n while (left < right) {\n if (lexicographicallySmallestPalindrome[left] < lexicographicallySmallestPalindrome[right]) {\n lexicographicallySmallestPalindrome[right] = lexicographicallySmallestPalindrome[left];\n } else {\n lexicographicallySmallestPalindrome[left] = lexicographicallySmallestPalindrome[right];\n }\n ++left;\n --right;\n }\n return lexicographicallySmallestPalindrome.join(\'\');\n};\n```\n```C++ []\n#include <string>\nusing namespace std;\n\nclass Solution {\n\npublic:\n string makeSmallestPalindrome(string s) const {\n string lexicographicallySmallestPalindrome = move(s);\n size_t left = 0;\n size_t right = lexicographicallySmallestPalindrome.size() - 1;\n\n while (left < right) {\n if (lexicographicallySmallestPalindrome[left] < lexicographicallySmallestPalindrome[right]) {\n lexicographicallySmallestPalindrome[right] = lexicographicallySmallestPalindrome[left];\n }\n else {\n lexicographicallySmallestPalindrome[left] = lexicographicallySmallestPalindrome[right];\n }\n ++left;\n --right;\n }\n return lexicographicallySmallestPalindrome;\n }\n};\n```\n```C# []\nusing System;\n\npublic class Solution\n{\n public string MakeSmallestPalindrome(string s)\n {\n char[] lexicographicallySmallestPalindrome = s.ToCharArray();\n int left = 0;\n int right = lexicographicallySmallestPalindrome.Length - 1;\n\n while (left < right)\n {\n if (lexicographicallySmallestPalindrome[left] < lexicographicallySmallestPalindrome[right])\n {\n lexicographicallySmallestPalindrome[right] = lexicographicallySmallestPalindrome[left];\n }\n else\n {\n lexicographicallySmallestPalindrome[left] = lexicographicallySmallestPalindrome[right];\n }\n ++left;\n --right;\n }\n return String.Join("", lexicographicallySmallestPalindrome);\n }\n}\n```\n```Kotlin []\nclass Solution {\n fun makeSmallestPalindrome(s: String): String {\n val lexicographicallySmallestPalindrome = s.toCharArray()\n var left = 0\n var right = lexicographicallySmallestPalindrome.size - 1\n\n while (left < right) {\n if (lexicographicallySmallestPalindrome[left] < lexicographicallySmallestPalindrome[right]) {\n lexicographicallySmallestPalindrome[right] = lexicographicallySmallestPalindrome[left]\n } else {\n lexicographicallySmallestPalindrome[left] = lexicographicallySmallestPalindrome[right]\n }\n ++left\n --right\n }\n return String(lexicographicallySmallestPalindrome)\n }\n}\n```\n```Go []\npackage main\n\nimport "fmt"\n\nfunc makeSmallestPalindrome(s string) string {\n lexicographicallySmallestPalindrome := []byte(s)\n left := 0\n right := len(lexicographicallySmallestPalindrome) - 1\n\n for left < right {\n if lexicographicallySmallestPalindrome[left] < lexicographicallySmallestPalindrome[right] {\n lexicographicallySmallestPalindrome[right] = lexicographicallySmallestPalindrome[left]\n } else {\n lexicographicallySmallestPalindrome[left] = lexicographicallySmallestPalindrome[right]\n }\n left++\n right--\n }\n return string(lexicographicallySmallestPalindrome)\n}\n```
1
0
['C++', 'Java', 'Go', 'TypeScript', 'Kotlin', 'JavaScript', 'C#']
0
lexicographically-smallest-palindrome
✅ Easy C++ Solution
easy-c-solution-by-moheat-8gzk
Code\n\nclass Solution {\npublic:\n string makeSmallestPalindrome(string s) {\n int n = s.size();\n int left = 0;\n int right = n-1;\n
moheat
NORMAL
2024-07-04T07:29:23.925560+00:00
2024-07-04T07:29:23.925595+00:00
225
false
# Code\n```\nclass Solution {\npublic:\n string makeSmallestPalindrome(string s) {\n int n = s.size();\n int left = 0;\n int right = n-1;\n while(left < right)\n {\n if(s[left] != s[right])\n {\n char most = (s[left] < s[right]) ? s[left] : s[right];\n s[left] = most;\n s[right] = most;\n }\n left++;\n right--;\n }\n return s;\n }\n};\n```
1
0
['C++']
0
lexicographically-smallest-palindrome
[Python] O(N) using two pointers
python-on-using-two-pointers-by-pbelskiy-r01l
\nclass Solution:\n def makeSmallestPalindrome(self, s: str) -> str:\n a = list(s)\n\n left, right = 0, len(a) - 1\n\n while left < righ
pbelskiy
NORMAL
2024-06-10T14:46:51.071769+00:00
2024-06-10T14:46:51.071807+00:00
40
false
```\nclass Solution:\n def makeSmallestPalindrome(self, s: str) -> str:\n a = list(s)\n\n left, right = 0, len(a) - 1\n\n while left < right:\n a[left] = a[right] = min(a[left], a[right])\n left += 1\n right -= 1\n \n return \'\'.join(a)\n```
1
0
['Two Pointers', 'Python']
0
lexicographically-smallest-palindrome
[Java] Easy 100% solution
java-easy-100-solution-by-ytchouar-zc45
java\nclass Solution {\n public String makeSmallestPalindrome(final String s) {\n final char str[] = s.toCharArray();\n int i = 0, j = s.length
YTchouar
NORMAL
2024-05-07T02:27:30.175283+00:00
2024-05-07T02:27:30.175310+00:00
228
false
```java\nclass Solution {\n public String makeSmallestPalindrome(final String s) {\n final char str[] = s.toCharArray();\n int i = 0, j = s.length() - 1;\n\n while(i < j) {\n str[i] = (char) Math.min(str[i], str[j]);\n str[j--] = str[i++];\n }\n\n return new String(str);\n \n }\n}\n```
1
0
['Java']
0
lexicographically-smallest-palindrome
Python solution, fast and intuitive
python-solution-fast-and-intuitive-by-se-kvm9
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
Semako123
NORMAL
2024-03-26T19:00:00.441896+00:00
2024-03-26T19:00:00.441921+00:00
120
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 makeSmallestPalindrome(self, s: str) -> str:\n tmp = list(s)\n start = 0\n end = len(s) - 1\n\n while start <= end:\n l = tmp[start]\n r = tmp[end]\n if l != r:\n change = l if l<r else r\n tmp[start], tmp[end] = change, change\n start += 1\n end -= 1\n\n return ("").join(tmp)\n \n```
1
0
['Python3']
0
lexicographically-smallest-palindrome
Simple java code 5 ms beats 100 %
simple-java-code-5-ms-beats-100-by-arobh-obaf
\n# Complexity\n- \n\n# Code\n\nclass Solution {\n public String makeSmallestPalindrome(String s) {\n int l = 0;\n int r = s.length() - 1;\n
Arobh
NORMAL
2024-01-31T15:09:38.763123+00:00
2024-01-31T15:09:38.763153+00:00
8
false
\n# Complexity\n- \n![image.png](https://assets.leetcode.com/users/images/72380c05-0fea-4248-8e3a-84ce7ef3b1b3_1706713762.7482114.png)\n# Code\n```\nclass Solution {\n public String makeSmallestPalindrome(String s) {\n int l = 0;\n int r = s.length() - 1;\n char[] arr = s.toCharArray();\n while (l < r) {\n if (arr[l] != arr[r]) {\n arr[r] = arr[l] = (char) Math.min(arr[l], arr[r]);\n }\n l++;\n r--;\n }\n return new String(arr);\n }\n}\n```
1
0
['Two Pointers', 'String', 'Java']
0
lexicographically-smallest-palindrome
java beats 100%
java-beats-100-by-susahin80-kw97
Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n\nclass Solution {\n public String makeSmallestPalindrome(String s) {\n c
susahin80
NORMAL
2023-11-19T13:24:18.031494+00:00
2023-11-19T13:24:18.031518+00:00
56
false
# Complexity\n- Time complexity:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\nclass Solution {\n public String makeSmallestPalindrome(String s) {\n char[] chars = s.toCharArray();\n int l = 0;\n int r = chars.length - 1;\n\n while (l < r) {\n int min = Math.min(chars[l], chars[r]);\n chars[l++] = chars[r--] = (char)min;\n }\n\n return new String(chars);\n }\n\n}\n```
1
0
['Java']
0
lexicographically-smallest-palindrome
Super easy solution in JS. WOW.
super-easy-solution-in-js-wow-by-azamata-v05d
\n# Code\n\n/**\n * @param {string} s\n * @return {string}\n */\nvar makeSmallestPalindrome = function(s) {\n let str = s.split(\'\')\n for(let i = s.leng
AzamatAbduvohidov
NORMAL
2023-08-12T05:15:02.754661+00:00
2023-08-12T05:15:02.754682+00:00
451
false
\n# Code\n```\n/**\n * @param {string} s\n * @return {string}\n */\nvar makeSmallestPalindrome = function(s) {\n let str = s.split(\'\')\n for(let i = s.length - 1, j = 0; i >= Math.ceil(s.length / 2); i--, j++) {\n if(str[i] < str[j]) {\n str[j] = str[i]\n } else {\n str[i] = str[j]\n }\n }\n return str.join(\'\')\n};\n```
1
0
['JavaScript']
0
lexicographically-smallest-palindrome
C# easy
c-easy-by-ghmarek-qiug
Code\n\npublic class Solution {\n public string MakeSmallestPalindrome(string s) {\n \n char[] sArr = s.ToArray();\n\n for (int i = 0, j
GHMarek
NORMAL
2023-06-27T15:01:03.500676+00:00
2023-06-27T15:01:03.500706+00:00
90
false
# Code\n```\npublic class Solution {\n public string MakeSmallestPalindrome(string s) {\n \n char[] sArr = s.ToArray();\n\n for (int i = 0, j = s.Length - 1; j >= s.Length / 2; j--, i++)\n {\n if (s[i] != s[j])\n {\n if (s[i] < s[j])\n {\n sArr[j] = s[i];\n\n continue;\n }\n\n sArr[i] = s[j];\n\n }\n }\n\n return new string(sArr);\n }\n}\n```
1
0
['C#']
0
lexicographically-smallest-palindrome
CPP || Easy Solution || 27 ms || 97%beats|| O(1) space || O(N) time
cpp-easy-solution-27-ms-97beats-o1-space-44ri
Intuition\n Describe your first thoughts on how to solve this problem. \nThe intuition is simple we have to make the string palindrome which is our first priori
aks1719
NORMAL
2023-05-30T17:03:35.279753+00:00
2023-05-30T17:04:08.777233+00:00
7
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe intuition is simple we have to make the string palindrome which is our first priority so simply i can check that it is palindrom or not and second task is that it should be Lexicographically Smallest Palindrome so when the string palindrom condition fails we can simply swap the largest amongst the two of them with the smallest\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\nI have used a simple loop and basic string palindrom checking condition that if s[i]!=s[s.size()-i-1] means there the string is different so we will compare if s[i] is smaller than s[s.size()-i-1] then we will set s[s.size()-i-1] as s[i] otherwise s[s.size()-i-1] is smaller that s[i] then s[i]= s[s.size()-i-1]\n\n# Complexity\n- Time complexity: $$O(N)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string makeSmallestPalindrome(string s) {\n for(int i= 0 ; i < s.size() ;i++)\n {\n if(s[i]!=s[s.size()-1-i])\n {\n if(s[i]<s[s.size()-1-i])\n {\n s[s.size()-1-i] = s[i];\n }\n else\n {\n s[i] = s[s.size()-1-i];\n }\n }\n }\n return s;\n }\n \n};\n```
1
0
['String', 'C++']
0
lexicographically-smallest-palindrome
JAVA | One pass
java-one-pass-by-sourin_bruh-63e2
Solution:\n\nclass Solution {\n public String makeSmallestPalindrome(String s) {\n int n = s.length();\n StringBuilder sb = new StringBuilder()
sourin_bruh
NORMAL
2023-05-23T17:32:25.872792+00:00
2023-05-23T17:32:25.872832+00:00
22
false
# Solution:\n```\nclass Solution {\n public String makeSmallestPalindrome(String s) {\n int n = s.length();\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < n; i++) {\n sb.append((char) Math.min(s.charAt(i), s.charAt(n - i - 1)));\n }\n return sb.toString();\n }\n}\n```\n### Time complexity: $$O(n)$$
1
0
['String', 'Java']
0
lexicographically-smallest-palindrome
python3; 214 ms; 16.5 MB
python3-214-ms-165-mb-by-nurmukhamed1-i7zh
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
Nurmukhamed1
NORMAL
2023-05-23T13:58:04.891049+00:00
2023-05-23T13:58:04.891097+00:00
858
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: 214 ms\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: 16.5 MB\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution:\n def makeSmallestPalindrome(self, s: str) -> str:\n before = 0\n after = len(s)-1\n l = [i for i in s]\n while before <= len(s)/2:\n l[before] = min(l[before], l[after])\n l[after] = l[before]\n before+=1\n after-=1\n return "".join(l)\n```
1
0
['Python3']
1
lexicographically-smallest-palindrome
Replace with Minimum
replace-with-minimum-by-_kitish-n30f
Code\n\nclass Solution {\npublic:\n string makeSmallestPalindrome(string s) {\n int n = size(s);\n for(int i=0; i<=n/2; ++i){\n if(s
_kitish
NORMAL
2023-05-21T19:58:03.065051+00:00
2023-05-21T19:58:03.065082+00:00
28
false
# Code\n```\nclass Solution {\npublic:\n string makeSmallestPalindrome(string s) {\n int n = size(s);\n for(int i=0; i<=n/2; ++i){\n if(s[i] != s[n-i-1]){\n char e = min(s[i],s[n-i-1]);\n s[i] = e;\n s[n-i-1] = e;\n }\n }\n return s;\n }\n};\n```
1
0
['C++']
0
lexicographically-smallest-palindrome
Two Pointer || Very easy to understand || Java
two-pointer-very-easy-to-understand-java-gvwl
\n# Approach\n Describe your approach to solving the problem. \n- Take two pointers, one at the 0th index and one at last index.\n- Check if the characters at b
sahilgupta8470
NORMAL
2023-05-21T10:45:40.904320+00:00
2023-05-21T10:45:40.904358+00:00
27
false
\n# Approach\n<!-- Describe your approach to solving the problem. -->\n- Take two pointers, one at the 0th index and one at last index.\n- Check if the characters at both pointers are same or not.\n- If not same, then check which character is lexicographically smaller.\n- Change the bigger character to smaller character.\n- Increment the first pointer and decrease the second one.\n# Complexity\n- Time complexity: O(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\n public String makeSmallestPalindrome(String s) {\n int i = 0, j = s.length()-1;\n while(i < j) {\n if(s.charAt(i) != s.charAt(j)) { \n if(s.charAt(i) < s.charAt(j)) { //Checking the lexicographically smaller character\n s = s.substring(0, j) + s.charAt(i) + s.substring(j+1); //changing the bigger character to smaller one\n }\n else {\n s = s.substring(0, i) + s.charAt(j) + s.substring(i+1);\n }\n }\n i++;\n j--;\n }\n return s;\n }\n}\n```
1
0
['Two Pointers', 'String', 'Java']
0
lexicographically-smallest-palindrome
C++ || EASY || SIMPLE
c-easy-simple-by-arya_ratan-1tfp
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
arya_ratan
NORMAL
2023-05-21T09:36:39.540465+00:00
2023-05-21T09:36:39.540569+00:00
33
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 string makeSmallestPalindrome(string s) {\n string t = s;\n reverse(t.begin(), t.end());\n string ans = "";\n for(int i=0;i<s.length();i++){\n if(s[i] == t[i]){\n ans.push_back(s[i]);\n }\n else{\n char m = min(s[i], t[i]);\n ans.push_back(m);\n }\n \n }\n return ans;\n }\n};\n```
1
0
['C++']
0
lexicographically-smallest-palindrome
Simple Easy Javascript Solution 100% beats 51.7 MB Memory
simple-easy-javascript-solution-100-beat-qz00
Code\n\n/**\n * @param {string} s\n * @return {string}\n */\nvar makeSmallestPalindrome = function(s) {\nlet newString = ""\nfor(let i=0 ; i< s.length ; i ++){\
dnt1997
NORMAL
2023-05-21T09:10:08.286742+00:00
2023-05-21T09:10:08.286784+00:00
154
false
# Code\n```\n/**\n * @param {string} s\n * @return {string}\n */\nvar makeSmallestPalindrome = function(s) {\nlet newString = ""\nfor(let i=0 ; i< s.length ; i ++){\n let firstWord = s.charAt(i);\n let lastWord = s.charAt(s.length -i - 1);\n if(firstWord!==lastWord){\n if(firstWord.charCodeAt(0)>lastWord.charCodeAt(0)){\n firstWord = lastWord\n }\n }\n newString = newString + firstWord \n}\nreturn(newString)\n\n \n};\n```
1
0
['JavaScript']
0
lexicographically-smallest-palindrome
Clean PY
clean-py-by-bariscan97-btvj
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-05-21T06:52:14.822036+00:00
2023-05-21T06:52:14.822076+00:00
559
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 makeSmallestPalindrome(self, s: str) -> str:\n r,l,s=len(s)-1,0,list(s)\n while r>l:\n if s[r]>s[l]:s[r]=s[l]\n else:s[l]=s[r]\n r-=1\n l+=1\n return "".join([i for i in s])\n```
1
1
['Array', 'String', 'String Matching', 'Python', 'Python3']
1
lexicographically-smallest-palindrome
c++ O(n) solution Two Pointers
c-on-solution-two-pointers-by-augus7-42o4
\n Describe your first thoughts on how to solve this problem. \n\n# Approach: Two Pointers\n Describe your approach to solving the problem. \n\n# Complexity\n-
Augus7
NORMAL
2023-05-21T05:25:35.524682+00:00
2023-05-21T05:25:35.524721+00:00
192
false
\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach: Two Pointers\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(n)$$ \n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string makeSmallestPalindrome(string s) {\n string ans = s; // because changing the given data is not good practice\n int i = 0, j = s.size() - 1;\n while(i < j) {\n if(ans[i] != ans[j]) {\n if(ans[i] < ans[j]) ans[j] = ans[i];\n else ans[i] = ans[j];\n }\n i++, j--;\n }\n return ans;\n }\n};\n```
1
0
['Two Pointers', 'String', 'C++']
1
lexicographically-smallest-palindrome
easy and simple solution
easy-and-simple-solution-by-rahul_pinto-v0zm
\n# Complexity\n- Time complexity:$O(n/2)$\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)
rahul_pinto
NORMAL
2023-05-21T05:23:58.680280+00:00
2023-05-21T05:23:58.680332+00:00
9
false
\n# Complexity\n- Time complexity:$O(n/2)$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:$O(1)$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string makeSmallestPalindrome(string s) \n {\n int first=0;\n int last=s.length()-1;\n while(first<=last)\n {\n if(s[first]!=s[last])\n {\n char k=min(s[first],s[last]);\n s[first]=k;\n s[last]=k;\n }\n first++;\n last--;\n \n }\n return s;\n }\n};\n```\n# upvote me if you like the solution comment if any doubts\n![images.jpeg](https://assets.leetcode.com/users/images/2996b8fb-ec16-4502-b820-a3705727a230_1684646601.8691707.jpeg)\n
1
0
['C++']
0
lexicographically-smallest-palindrome
Simple Solution || Easy To Understand
simple-solution-easy-to-understand-by-dc-8iez
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
Dcoder_53
NORMAL
2023-05-21T04:30:53.975457+00:00
2023-05-25T07:07:36.858883+00:00
84
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:O(n)\n\n- Space complexity:O(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n string makeSmallestPalindrome(string s) {\n int n=s.size();\n for(int i=0 ; i < n/2 ; i++){\n char a=s[i];\n char b=s[s.size()-i-1];\n char mini=min(a,b);\n s[i]=mini;\n s[s.size()-i-1]=mini;\n }\n return s;\n }\n};\n```
1
0
['C++']
1
lexicographically-smallest-palindrome
Simple Two Pointer Solution | Java
simple-two-pointer-solution-java-by-raja-gvyl
Approach: Take two pointers one at 0 index other at last-1 at each iteration replace the large character with smaller one in stringbuilder return the string at
Rajat069
NORMAL
2023-05-21T04:24:59.268776+00:00
2023-05-21T04:24:59.268803+00:00
115
false
**Approach:** Take two pointers one at 0 index other at last-1 at each iteration replace the large character with smaller one in stringbuilder return the string at last.\n```\nclass Solution {\n public String makeSmallestPalindrome(String s) {\n StringBuilder sb = new StringBuilder(s);\n int f=0,l=s.length()-1;\n while(f<l){\n if(s.charAt(f)>s.charAt(l)){\n sb.replace(f,f+1,s.charAt(l)+""); \n }\n else sb.replace(l,l+1,s.charAt(f)+"");\n f++;\n l--;\n }\n return sb.toString();\n }\n}
1
0
['Java']
0
lexicographically-smallest-palindrome
Beats 100% Solutions
beats-100-solutions-by-deleted_user-vn95
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-05-21T04:23:11.268618+00:00
2023-05-21T04:23:11.268661+00:00
171
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:\nO(n)\n\n- Space complexity:\nO(n)\n\n# Code\n```\n/**\n * @param {string} s\n * @return {string}\n */\nvar makeSmallestPalindrome = function(s) {\n \n let rev = s.split("").reverse().join("");\n let str = \'\';\n\n for(let i = 0 ; i < s.length ; i++)\n {\n const item1 = s[i];\n const item2 = rev[i];\n\n if( item1 === item2 )\n {\n str += item1;\n }\n else\n {\n if(s.charCodeAt(i) < rev.charCodeAt(i))\n {\n str += item1;\n }\n else\n {\n str += item2;\n }\n }\n }\n return str;\n \n};\n```
1
0
['JavaScript']
1
lexicographically-smallest-palindrome
Lexicographically Smallest Palindrome || C++
lexicographically-smallest-palindrome-c-2feat
\n# Code\n\nclass Solution {\npublic:\n string makeSmallestPalindrome(string s) {\n int i=0;\n int j=s.size()-1;\n \n while(i<j){\n
krish_kakadiya
NORMAL
2023-05-21T04:18:20.769805+00:00
2023-05-21T04:18:20.769847+00:00
367
false
\n# Code\n```\nclass Solution {\npublic:\n string makeSmallestPalindrome(string s) {\n int i=0;\n int j=s.size()-1;\n \n while(i<j){\n if(s[i]!=s[j]){\n if(int(s[i])>int(s[j])) s[i]=s[j];\n else s[j]=s[i];\n }\n i++;\n j--;\n }\n return s;\n }\n};\n```
1
0
['C++']
0
lexicographically-smallest-palindrome
Simple C++ Solution
simple-c-solution-by-roytanmay-5fia
Intuition\n Describe your first thoughts on how to solve this problem. \nTake the smallest from s[i] and s[n-i-1] for every index (0 <= i < n/2)\n\n# Complexit
roytanmay
NORMAL
2023-05-21T04:13:16.982851+00:00
2023-05-21T04:13:16.982887+00:00
11
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nTake the smallest from s[i] and s[n-i-1] for every index (0 <= i < n/2)\n\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n\n# Code\n```\nclass Solution {\npublic:\n string makeSmallestPalindrome(string s) {\n int n = s.size();\n for(int i=0; i<n/2; i++)\n {\n if(s[i] > s[n-i-1]) s[i] = s[n-i-1];\n else s[n-i-1] = s[i];\n }\n return s;\n }\n};\n```
1
0
['C++']
0
lexicographically-smallest-palindrome
very simple and easy to understand solution
very-simple-and-easy-to-understand-solut-1z2q
\n\n# Code\n\nclass Solution:\n def makeSmallestPalindrome(self, s: str) -> str:\n def helper(s) :\n if len(s) <2 :\n return
Vivek_Raj_
NORMAL
2023-05-21T04:09:49.544557+00:00
2023-05-21T04:09:49.544589+00:00
358
false
\n\n# Code\n```\nclass Solution:\n def makeSmallestPalindrome(self, s: str) -> str:\n def helper(s) :\n if len(s) <2 :\n return s\n \n \n if ord(s[0]) <= ord(s[-1]) :\n return s[0] + helper(s[1:len(s)-1]) +s[0]\n else :\n return s[-1]+helper(s[1:len(s)-1]) + s[-1]\n \n \n return helper(s)\n \n \n \n```
1
1
['Python3']
1
lexicographically-smallest-palindrome
Check if you need to change character, if yes, change to smaller
check-if-you-need-to-change-character-if-1mkb
Intuition\nCheck for every position until the half of the string, check if elements are the same:\n - if yes, nothing to be done\n - if no, modify one of them b
salvadordali
NORMAL
2023-05-21T04:04:33.281796+00:00
2023-05-21T04:24:38.147928+00:00
801
false
# Intuition\nCheck for every position until the half of the string, check if elements are the same:\n - if yes, nothing to be done\n - if no, modify one of them by changing it to a smaller character\n\n\n\n# Complexity\n- Time complexity: $O(n)$\n- Space complexity: $O(n)$\n\n# Code\n\n```Rust []\nimpl Solution {\n pub fn make_smallest_palindrome(s: String) -> String {\n let l = s.len();\n let mut s: Vec<char> = s.chars().collect();\n for i in 0 .. l / 2 {\n if s[i] != s[l - i - 1] {\n let v = s[i].min(s[l - i - 1]);\n s[i] = v;\n s[l - i - 1] = v;\n }\n }\n\n return s.into_iter().collect();\n }\n}\n```\n```python []\nclass Solution:\n def makeSmallestPalindrome(self, s: str) -> str:\n s, l = list(s), len(s)\n for i in range(l // 2):\n if s[i] != s[l - i - 1]:\n c = min(s[i], s[l - i - 1])\n s[i], s[l - i - 1] = c, c\n \n return \'\'.join(s)\n```\n
1
0
['Python3', 'Rust']
0
lexicographically-smallest-palindrome
Two pointer Approach only EASY TO UNDERSTAND
two-pointer-approach-only-easy-to-unders-oj0t
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
ajayadhikari
NORMAL
2023-05-21T04:03:17.383166+00:00
2023-05-21T04:03:17.383225+00:00
20
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 string makeSmallestPalindrome(string s) {\n string p = s;\n int left = 0;\n int r = s.length() - 1;\n\n while (left < r) {\n if (p[left] != p[r]) {\n p[r] = p[left] = std::min(p[left], p[r]);\n }\n left++;\n r--;\n }\n\n return p;\n \n }\n};\n```
1
1
['Python', 'C++', 'Java', 'Python3', 'MS SQL Server']
0
lexicographically-smallest-palindrome
Very simple and Easy Solution⚡🔥🔥
very-simple-and-easy-solution-by-yashpad-gjaj
\n# Code\n\nclass Solution {\npublic:\n string makeSmallestPalindrome(string s) {\n int i=0;\n int j=s.size()-1;\n \n \n s
yashpadiyar4
NORMAL
2023-05-21T04:02:46.446588+00:00
2023-05-21T04:02:46.446623+00:00
149
false
\n# Code\n```\nclass Solution {\npublic:\n string makeSmallestPalindrome(string s) {\n int i=0;\n int j=s.size()-1;\n \n \n string ans;\n while(i<j){\n if(s[i]!=s[j]){\n ans+=min(s[i],s[j]);\n }\n else{\n ans+=s[i];\n }\n i++;\n j--;\n }\n string q=ans;\n reverse(q.begin(),q.end());\n \n int n=s.size();\n if(n%2)ans+=s[n/2];\n ans+=q;\n return ans;\n \n \n }\n};\n```
1
0
['C++']
1
lexicographically-smallest-palindrome
Java || O(n)
java-on-by-nishant7372-4wkj
java []\nclass Solution {\n public String makeSmallestPalindrome(String s) {\n int i=0;\n int j=s.length()-1;\n char[] arr = s.toCharArr
nishant7372
NORMAL
2023-05-21T04:02:41.640210+00:00
2023-05-21T04:02:41.640247+00:00
721
false
``` java []\nclass Solution {\n public String makeSmallestPalindrome(String s) {\n int i=0;\n int j=s.length()-1;\n char[] arr = s.toCharArray();\n while(i<=j){\n if(arr[i]!=arr[j]){\n arr[i] = arr[j] = (char) Math.min(arr[i],arr[j]);\n }\n i++;\n j--;\n }\n return new String(arr);\n }\n}\n```
1
0
['Java']
0
lexicographically-smallest-palindrome
Java
java-by-neel_diyora-qgl8
Code\n\nclass Solution {\n public String makeSmallestPalindrome(String s) {\n char[] ch = s.toCharArray();\n int start = 0;\n int end =
anjan_diyora
NORMAL
2023-05-21T04:02:33.206016+00:00
2023-05-21T04:02:33.206057+00:00
249
false
# Code\n```\nclass Solution {\n public String makeSmallestPalindrome(String s) {\n char[] ch = s.toCharArray();\n int start = 0;\n int end = s.length() - 1;\n \n while(start <= end) {\n if(ch[start] != ch[end]) {\n if(ch[end] > ch[start]) {\n ch[end] = ch[start];\n } else {\n ch[start] = ch[end];\n }\n }\n start++;\n end--;\n }\n \n return String.valueOf(ch);\n }\n}\n```
1
0
['Java']
0
lexicographically-smallest-palindrome
4 ms Beats 62.22%
4-ms-beats-6222-by-bvc01654-n1z0
IntuitionApproachComplexity Time complexity:O(N) Space complexity:O(1) Code
bvc01654
NORMAL
2025-04-09T18:36:47.031966+00:00
2025-04-09T18:36:47.031966+00:00
1
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity:O(N) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity:O(1) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] #define fast ios_base::sync_with_stdio(false);cin.tie(nullptr); class Solution { public: string makeSmallestPalindrome(string s) { fast for(int i=0;i<s.length()/2;i++) { if(s[i]==s[s.length()-i-1]) continue; if(s[i]<s[s.length()-i-1]) s[s.length()-i-1]=s[i]; if(s[i]>s[s.length()-i-1]) s[i]=s[s.length()-i-1]; } return s; } }; ```
0
0
['C++']
0
lexicographically-smallest-palindrome
Lexicographically Smallest Palindrome
lexicographically-smallest-palindrome-by-fy9j
IntuitionApproachComplexity Time complexity: Space complexity: Code
jyenduri
NORMAL
2025-04-07T18:08:50.653600+00:00
2025-04-07T18:08:50.653600+00:00
1
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 ```golang [] func makeSmallestPalindrome(s string) string { // num := 0 runes := []rune(s) for i,j := 0, len(s)-1; i<j; i,j= i+1, j-1 { if(runes[i]!= runes[j] ){ if runes[i] > runes[j] { runes[i]= runes[j] }else{ runes[j]= runes[i] } } } return string(runes) } ```
0
0
['Go']
0
lexicographically-smallest-palindrome
Simple Java Code using 2 pointer
simple-java-code-using-2-pointer-by-kaly-o5k3
IntuitionApproachComplexity Time complexity: O(n) Space complexity: O(n) Code
kalyanram2053
NORMAL
2025-04-07T12:18:38.351341+00:00
2025-04-07T12:18:38.351341+00:00
1
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(n) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(n) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public String makeSmallestPalindrome(String s) { int st=0; int end=s.length()-1; char[] arr=s.toCharArray(); while(st<end){ if(arr[st]<arr[end]){ arr[end]=arr[st]; }else{ arr[st]=arr[end]; } st++; end--; } return new String(arr); } } ```
0
0
['Java']
0
lexicographically-smallest-palindrome
JAVA TWO POINTER APPROACH
java-two-pointer-approach-by-rohit-baba-cc2u
IntuitionApproachComplexity Time complexity: O(n) Space complexity: O(n) Code
Rohit-Baba
NORMAL
2025-04-05T06:39:22.363653+00:00
2025-04-05T06:39:22.363653+00:00
1
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(n) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: O(n) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public String makeSmallestPalindrome(String s) { int n = s.length(); char ch[] = s.toCharArray(); int i = 0; int j = n-1; while(i < j) { if(ch[i] != ch[j]) { char c; if(ch[i] < ch[j]) { c = ch[i]; } else { c = ch[j]; } ch[i] = ch[j] = c; } i++; j--; } return new String(ch); } } ```
0
0
['Two Pointers', 'Java']
0
lexicographically-smallest-palindrome
simple solution|| using two pointers
simple-solution-using-two-pointers-by-ko-aojd
IntuitionApproachComplexity Time complexity: Space complexity: Code
kotla_jithendra
NORMAL
2025-03-31T06:44:01.186389+00:00
2025-03-31T06:44:01.186389+00:00
3
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 makeSmallestPalindrome(self, s: str) -> str: l=0 r=len(s)-1 res=[i for i in s] while l<r: if ord(s[l])<ord(s[r]): res[l]=s[l] res[r]=s[l] elif ord(s[l])>ord(s[r]): res[l]=s[r] res[r]=s[r] l+=1 r-=1 return "".join(res) ```
0
0
['Two Pointers', 'String', 'Python3']
0
lexicographically-smallest-palindrome
🔥✅✅ Dart Solution 📌📌 || with Explanation 👌👌
dart-solution-with-explanation-by-nosar-435b
Solution Two-Pointer Technique: We'll use two pointers starting from both ends of the string and move towards the center. Character Comparison: At each step, we
NosaR
NORMAL
2025-03-26T00:57:08.564786+00:00
2025-03-26T00:57:08.564786+00:00
2
false
# Solution 1. **Two-Pointer Technique**: We'll use two pointers starting from both ends of the string and move towards the center. 2. **Character Comparison**: At each step, we compare the characters at both pointers: - If they are different, we need to replace one of them to make them match. - To ensure lexicographical smallest, we'll always replace the larger character with the smaller one. 3. **Middle Character Handling**: If the string length is odd, the middle character can be left as is since it doesn't affect the palindrome property. ## Time Complexity - **O(n)**: We process each character in the string exactly once using the two-pointer approach, where n is the length of the string. The comparison and replacement operations are constant time for each character pair. ```dart class Solution { String makeSmallestPalindrome(String s) { List<String> chars = s.split(''); int left = 0; int right = s.length - 1; while (left < right) { if (chars[left] != chars[right]) { if (chars[left].compareTo(chars[right]) < 0) { chars[right] = chars[left]; } else { chars[left] = chars[right]; } } left++; right--; } return chars.join(''); } } ```
0
0
['Dart']
0
lexicographically-smallest-palindrome
Java, beats 83.93%, 6ms
java-beats-8393-6ms-by-nivet101-9muq
IntuitionIf we have two pointer moving inward from both ends when we encounter different characters, we choose the smaller of the two.Complexity Time complexity
nivet101
NORMAL
2025-03-24T19:05:50.477591+00:00
2025-03-24T19:05:50.477591+00:00
3
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> If we have two pointer moving inward from both ends when we encounter different characters, we choose the smaller of the two. # Complexity - Time complexity:$$O(n)$$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity:$$O(1)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public String makeSmallestPalindrome(String s) { char[] arr = s.toCharArray(); int i = 0; int j = arr.length - 1; while(i <= j) { if((int) arr[i] < (int) arr[j]) { arr[j] = arr[i]; }else { arr[i] = arr[j]; } i++; j--; } return new String(arr); } } ```
0
0
['Java']
0
lexicographically-smallest-palindrome
MinChar solution
minchar-solution-by-ezpectus-i48a
What's a Palindrome?First, a palindrome is a word or phrase that reads the same forwards and backward. For example, "racecar" and "madam" are palindromes.The Pr
ezpectus
NORMAL
2025-03-24T10:39:19.254762+00:00
2025-03-24T10:39:19.254762+00:00
2
false
What's a Palindrome? First, a palindrome is a word or phrase that reads the same forwards and backward. For example, "racecar" and "madam" are palindromes. The Problem: You're given a string s. Your job is to change some of the characters in s so that it becomes a palindrome. But, you want to make the "smallest" palindrome possible. "Smallest" here means if you compare two palindromes character by character, the one with the earlier letter in the alphabet at the first point they differ is considered smaller. How the Code Works: Convert to Character Array: char[] arr = s.ToCharArray(); The code turns the input string s into an array of characters called arr. This is because it's easier to change individual characters in an array. Two Pointers: int left = 0; and int right = s.Length - 1; The code sets up two "pointers," left and right. left starts at the beginning of the array, and right starts at the end. Loop and Compare: while (left < right) The code loops as long as the left pointer is before the right pointer. if (arr[left] != arr[right]) Inside the loop, it checks if the characters at the left and right positions are different. char minchr = (char)Math.Min(arr[left], arr[right]); If they're different, it finds the smaller of the two characters (the one that comes earlier in the alphabet). arr[left] = arr[right] = minchr; Then, it changes both the left and right characters to this smaller character. This ensures the string becomes a palindrome. Move Pointers: left++; and right--; The left pointer moves one position to the right, and the right pointer moves one position to the left. Create New String: return new string(arr); Finally, the code creates a new string from the modified character array arr and returns it. Example: Let's say s is "egcfe". arr becomes ['e', 'g', 'c', 'f', 'e']. left is 0, right is 4. arr[0] ('e') is the same as arr[4] ('e'). left becomes 1, right becomes 3. arr[1] ('g') is different from arr[3] ('f'). minchr is 'f'. arr[1] and arr[3] both become 'f'. arr is now ['e', 'f', 'c', 'f', 'e']. left becomes 2, right becomes 2. The loop ends. The code returns "efcfe". Complexity: Time Complexity: O(n) The code goes through the string once, so the time it takes is proportional to the length of the string. Space Complexity: O(n) The character array arr takes up space proportional to the length of the string. # Code ```csharp [] public class Solution { public string MakeSmallestPalindrome(string s) { char[] arr = s.ToCharArray(); int left = 0; int right = s.Length-1; while( left<right){ if(arr[left] != arr[right]){ char minchr = (char)Math.Min(arr[left],arr[right]); arr[left] = arr[right] = minchr; } left++; right--; } return new string(arr); } } ```
0
0
['Two Pointers', 'String', 'Greedy', 'C++', 'C#']
0
lexicographically-smallest-palindrome
JavaScript, beats 81.44%, 22ms
javascript-beats-8144-22ms-by-nivet101-g5st
IntuitionIf we have two pointer moving inward from both ends when we encounter different characters, we choose the smaller of the two.Complexity Time complexity
nivet101
NORMAL
2025-03-24T02:32:54.977325+00:00
2025-03-24T02:32:54.977325+00:00
6
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> If we have two pointer moving inward from both ends when we encounter different characters, we choose the smaller of the two. # Complexity - Time complexity:$$O(n)$$ <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity:$$O(1)$$ <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```javascript [] /** * @param {string} s * @return {string} */ var makeSmallestPalindrome = function(s) { let i = 0; let j = s.length-1; s = s.split(''); while(i <= j) { if(s[i] < s[j]) { s[j] = s[i]; }else { s[i] = s[j]; } i++; j--; } return s.join('') }; // abc -> aba NOT cbc //Intuition // if we have two pointer moving inward from both ends // when we encounter different characters, we choose the smaller of the two to insert in the other position ```
0
0
['JavaScript']
0
lexicographically-smallest-palindrome
Easy to understand solution in Java. Beats 84.11 %
easy-to-understand-solution-in-java-beat-qlok
Complexity Time complexity: O(n) Space complexity: O(n) Code
Khamdam
NORMAL
2025-03-21T15:42:33.499081+00:00
2025-03-21T15:42:33.499081+00:00
2
false
# Complexity - Time complexity: O(n) - Space complexity: O(n) # Code ```java [] class Solution { public String makeSmallestPalindrome(String s) { char[] chars = s.toCharArray(); int left = 0; int right = chars.length - 1; while (left < right) { if (chars[left] < chars[right]) { chars[right] = chars[left]; left++; right--; } else { chars[left] = chars[right]; left++; right--; } } return new String(chars); } } ```
0
0
['Two Pointers', 'String', 'Java']
0
lexicographically-smallest-palindrome
Optimized simple solution - beats 83.59%🔥
optimized-simple-solution-beats-8359-by-n9lwm
IntuitionApproachComplexity Time complexity: O(N) Space complexity: O(N) Code
cyrusjetson
NORMAL
2025-03-18T11:15:51.510235+00:00
2025-03-18T11:15:51.510235+00:00
4
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: O(N) - Space complexity: O(N) # Code ```java [] class Solution { public String makeSmallestPalindrome(String s) { char[] t = s.toCharArray(); int i = 0; int j = t.length - 1; while (i < j) { if (t[i] < t[j]) { t[j] = t[i]; } else if (t[i] > t[j]) { t[i] = t[j]; } i++; j--; } return new String(t); } } ```
0
0
['Java']
0
lexicographically-smallest-palindrome
C++ | 2 Pointer
c-2-pointer-by-kena7-lva2
Code
kenA7
NORMAL
2025-03-17T13:40:04.263458+00:00
2025-03-17T13:40:04.263458+00:00
3
false
# Code ```cpp [] class Solution { public: string makeSmallestPalindrome(string s) { int i=0,j=s.size()-1; while(i<j) { if(s[i]!=s[j]) { if(s[i]<s[j]) s[j]=s[i]; else s[i]=s[j]; } i++; j--; } return s; } }; ```
0
0
['C++']
0
lexicographically-smallest-palindrome
C++ | Simple 0 ms 5 lines solution beats submitted solutions 100% in runtime and 90% in memory
c-simple-0-ms-5-lines-solution-beats-sub-qrwe
IntuitionReplace the twin characters with the smaller one if they are not equal.ApproachParse the string character by character till the mid of the string. Comp
thoka5pointsomeone
NORMAL
2025-03-16T10:21:17.389066+00:00
2025-03-16T10:21:17.389066+00:00
3
false
# Intuition Replace the twin characters with the smaller one if they are not equal. # Approach Parse the string character by character till the mid of the string. Compare each character at a specific position from the beginning with the character at the same position from the end of the string. If the characters are not equal replace the lexicographically larger character with the lexicographically smaller character. Repeat this process till you reach the middle of the string. # Complexity - Time complexity for `n` characters in the string: $$O(n)$$ - Space complexity for `n` characters in the string: $$O(1)$$ # Code ```cpp [] class Solution { public: string makeSmallestPalindrome(string s) { const int n = s.size(); for (int i=0; i<n/2; ++i) { if (s[i] == s[n-1-i]) continue; if (s[i] < s[n-1-i]) s[n-1-i] = s[i]; else s[i] = s[n-1-i]; } return s; } }; ```
0
0
['C++']
0
lexicographically-smallest-palindrome
Easy and Simple Solution to understand
easy-and-simple-solution-to-understand-b-jkgo
IntuitionA palindrome is a string that reads the same forward and backward. Our goal is to convert the given string into the lexicographically smallest palindro
gane0519
NORMAL
2025-03-15T09:39:02.376521+00:00
2025-03-15T09:39:02.376521+00:00
5
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> A palindrome is a string that reads the same forward and backward. Our goal is to convert the given string into the lexicographically smallest palindrome with minimal modifications. To achieve this, we use a two-pointer approach: 1. Compare characters from both ends (left and right). 1. If they are different, replace the larger character with the smaller one to get the smallest lexicographical order. 1. Continue this process until we process the entire string. # Approach <!-- Describe your approach to solving the problem. --> 1. Initialize Two Pointers: - left = 0 (starting index) - right = s.length() - 1 (ending index) 2. Use a StringBuilder for Mutability: - Since String is immutable in Java, we use StringBuilder to modify characters efficiently. 3. Iterate Until left Meets right: - If s.charAt(left) == s.charAt(right), move both pointers inward. If they are different: - Replace the larger character with the smaller one to ensure lexicographically smallest order. - Modify sb accordingly. 4. Return the Modified String: - After processing all characters, return sb.toString(). # Complexity - Time complexity:O(n) <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity:O(n) <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```java [] class Solution { public String makeSmallestPalindrome(String s) { int left = 0; int right = s.length() - 1; StringBuilder sb = new StringBuilder(s); while (left < right) { if (s.charAt(left) != s.charAt(right)) { if (s.charAt(left) > s.charAt(right)) { sb.setCharAt(left, s.charAt(right)); } else { sb.setCharAt(right, s.charAt(left)); } } left++; right--; } return sb.toString(); } } ```
0
0
['Two Pointers', 'String', 'Java']
0
lexicographically-smallest-palindrome
Simple straight forward two pointers
simple-straight-forward-two-pointers-by-hltto
Code
user9878Nx
NORMAL
2025-03-13T17:18:37.468881+00:00
2025-03-13T17:18:37.468881+00:00
3
false
# Code ```swift [] class Solution { func makeSmallestPalindrome(_ s: String) -> String { var chars = Array(s) var i = 0 var j = chars.count - 1 while i < j { if chars[i] < chars[j] { chars[j] = chars[i] } else { chars[i] = chars[j] } i += 1 j -= 1 } return String(chars) } } ```
0
0
['Swift']
0
lexicographically-smallest-palindrome
byte performs better than rune
byte-performs-better-than-rune-by-wiiken-vqvd
IntuitionApproachComplexity Time complexity: Space complexity: Code
wiikend
NORMAL
2025-03-07T17:40:33.333889+00:00
2025-03-07T17:40:33.333889+00:00
4
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 ```golang [] import "fmt" func makeSmallestPalindrome(s string) string { r := []byte(s) for i, j := 0, len(r) - 1; i < j; i, j = i+1, j-1 { if r[i] < r[j] { r[j] = r[i] } else { r[i] = r[j] } } return string(r) } ```
0
0
['Go']
0
lexicographically-smallest-palindrome
easy to understand
easy-to-understand-by-budu123-p7fj
IntuitionApproachComplexity Time complexity: Space complexity: Code
budu123
NORMAL
2025-03-04T20:07:52.547156+00:00
2025-03-04T20:07:52.547156+00:00
3
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: string makeSmallestPalindrome(string &s) { int left = 0; int right = s.size() -1 ; while (right>left){ if (s[left]!=s[right]){ if(s[left]>s[right]) s[left]=s[right]; else s[right]=s[left]; } --right; ++left; } return s; } }; ```
0
0
['C++']
0
lexicographically-smallest-palindrome
Easier way to solve this problem
easier-way-to-solve-this-problem-by-shia-lonv
ApproachFor all mirror-symmetric elements in the string, select the smaller one and use it as a replacement for both. For example, given the string "abcd", we w
ShiaoC
NORMAL
2025-03-02T04:06:03.263408+00:00
2025-03-02T04:06:03.263408+00:00
1
false
# Approach <!-- Describe your approach to solving the problem. --> For all mirror-symmetric elements in the string, select the smaller one and use it as a replacement for both. > For example, given the string "abcd", we will first compare 'a' and 'd', as they are closest to the beginning and end of the string. Since 'a' is smaller than 'd', we replace 'd' with 'a'. --- # Complexity - Time complexity:O(n) <!-- 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: string makeSmallestPalindrome(string s) { int n = s.size(); for(int i = 0; i< (n>>1); i++){ s[i] = min(s[i], s[n-i-1]); s[n-i-1] = s[i]; } return s; } }; ```
0
0
['C++']
0
lexicographically-smallest-palindrome
Lexicographically Smallest Palindrome Using Two-Pointer Approach
lexicographically-smallest-palindrome-us-hjd5
IntuitionA palindrome is a string that reads the same forward and backward. To transform a given string into a lexicographically smallest palindrome, we need to
rabdya_767
NORMAL
2025-03-01T09:02:43.925248+00:00
2025-03-01T09:02:43.925248+00:00
5
false
--- # **Intuition** A **palindrome** is a string that reads the same forward and backward. To transform a given string into a **lexicographically smallest palindrome**, we need to modify the characters while ensuring minimal changes. A **lexicographically smaller** string means that, when comparing two characters, we replace the larger one with the smaller one to ensure the smallest possible result. --- # **Approach** 1. **Use Two Pointers:** - Start with `i = 0` (leftmost character) and `j = s.length - 1` (rightmost character). - Move `i` forward and `j` backward, ensuring that characters at `i` and `j` match. 2. **Modify the String In-Place:** - If `s[i] != s[j]`, replace both with the **smaller** character (`min(s[i], s[j])`). - This ensures the lexicographically smallest result while making the string a palindrome. 3. **Convert Back to String:** - Since strings are immutable in JavaScript, we first convert `s` into an array (`arr`) for modification. - After processing, we join the array back into a string. --- # **Complexity Analysis** - **Time Complexity:** **\( O(n) \)** - We traverse the string **once**, comparing and modifying characters, leading to linear time complexity. - **Space Complexity:** **\( O(n) \)** - We create an array `arr` of size `n` to modify characters, leading to linear space complexity. - However, if **mutability of the input string** were allowed, we could achieve **\( O(1) \)** space complexity. --- # **Code** ```javascript /** * @param {string} s * @return {string} */ var makeSmallestPalindrome = function(s) { let i = 0, j = s.length - 1; let arr = Array.from(s); // Convert string to array for modification while (i <= j) { if (arr[i] !== arr[j]) { const minChar = arr[i] < arr[j] ? arr[i] : arr[j]; // Choose the smaller character arr[i] = arr[j] = minChar; // Assign the same value to both sides } i++; j--; } return arr.join(""); // Convert array back to string }; // Example Test Cases console.log(makeSmallestPalindrome("egcfe")); // Output: "efcfe" console.log(makeSmallestPalindrome("abcd")); // Output: "abba" console.log(makeSmallestPalindrome("race")); // Output: "eace" console.log(makeSmallestPalindrome("madam")); // Output: "madam" (Already a palindrome) ``` --- # **Example Walkthrough** ### **Example 1:** #### **Input:** `"egcfe"` #### **Processing Steps:** | i | j | arr[i] | arr[j] | Modification | Updated String | |---|---|--------|--------|--------------|----------------| | 0 | 4 | 'e' | 'e' | No change | "egcfe" | | 1 | 3 | 'g' | 'f' | Replace with 'f' | "efcfe" | | 2 | 2 | 'c' | 'c' | No change | "efcfe" | #### **Output:** `"efcfe"` --- ### **Example 2:** #### **Input:** `"abcd"` #### **Processing:** | i | j | arr[i] | arr[j] | Modification | Updated String | |---|---|--------|--------|--------------|----------------| | 0 | 3 | 'a' | 'd' | Replace 'd' with 'a' | "abca" | | 1 | 2 | 'b' | 'c' | Replace 'c' with 'b' | "abba" | #### **Output:** `"abba"` --- # **Summary** ✅ Uses the **two-pointer approach** to efficiently transform the string. ✅ Ensures the **lexicographically smallest** palindrome with minimal modifications. ✅ Achieves **\( O(n) \) time complexity** and **\( O(n) \) space complexity**. ✅ Works for **both even- and odd-length strings**.
0
0
['JavaScript']
0
lexicographically-smallest-palindrome
Lexicographically Smallest Palindrome Transformation
lexicographically-smallest-palindrome-tr-6c8q
IntuitionThe goal is to transform the given string into the lexicographically smallest palindrome by modifying characters as needed. Since a palindrome reads th
rabdya_767
NORMAL
2025-03-01T08:59:02.136845+00:00
2025-03-01T08:59:02.136845+00:00
3
false
--- # **Intuition** The goal is to transform the given string into the **lexicographically smallest palindrome** by modifying characters as needed. Since a palindrome reads the same forward and backward, we can compare corresponding characters from both ends and replace the larger one with the smaller one. --- # **Approach** 1. Convert the input string into an array (`arr`) so we can modify characters efficiently. 2. Use two pointers: - `i` starts from the beginning (`0`). - `j` starts from the end (`s.length - 1`). 3. Iterate while `i <= j`: - If `arr[i] !== arr[j]`, replace both characters with the **smaller** one to ensure lexicographical order. - Move the pointers (`i++` and `j--`) toward the center. 4. Convert the modified array back into a string and return it. --- # **Complexity Analysis** - **Time Complexity:** $$O(n)$$, as we iterate through the string once. - **Space Complexity:** $$O(n)$$, due to converting the string into an array. --- # **Code** ```javascript /** * @param {string} s * @return {string} */ var makeSmallestPalindrome = function(s) { let i = 0, j = s.length - 1; let arr = s.split(""); // Convert string to array while (i <= j) { if (arr[i] !== arr[j]) { const minChar = arr[i] < arr[j] ? arr[i] : arr[j]; // Choose the smaller character arr[i] = arr[j] = minChar; // Make them equal } i++; j--; } return arr.join(""); // Convert array back to string }; // Example console.log(makeSmallestPalindrome("egcfe")); // Output: "efcfe" ``` --- # **Example Walkthrough** ### **Input:** `"egcfe"` ### **Step-by-step transformation:** 1. Compare `s[0] = 'e'` and `s[4] = 'e'` → No change. 2. Compare `s[1] = 'g'` and `s[3] = 'f'` → Replace both with `'f'`, result: `"efcfe"`. 3. `s[2] = 'c'` is in the middle → No change needed. 4. Final palindrome: `"efcfe"`. --- This approach guarantees the **lexicographically smallest** palindrome transformation while maintaining efficiency. 🚀
0
0
['JavaScript']
0
lexicographically-smallest-palindrome
python code
python-code-by-vishalyadav28-pvlc
ApproachTwo pointer opposite directionComplexity Time complexity: O(N) Space complexity: O(N) Code
vishalyadav28
NORMAL
2025-02-27T09:21:22.377650+00:00
2025-02-27T09:21:22.377650+00:00
5
false
# Approach Two pointer opposite direction # Complexity - Time complexity: $$O(N)$$ - Space complexity: $$O(N)$$ # Code ```python3 [] class Solution: def makeSmallestPalindrome(self, s: str) -> str: # sl = list(s) # left=0 # right=len(sl)-1 # while left<right: # if sl[left] != sl[right]: # sl[left] = sl[right] = min(sl[left], sl[right]) # left+=1 # right-=1 # return ''.join(sl) sl = list(s) left=0 right=len(sl)-1 while left<right: if sl[left] != sl[right]: if sl[left] > sl[right]: sl[left] = sl[right] else: sl[right]=sl[left] left+=1 right-=1 return ''.join(sl) ```
0
0
['Two Pointers', 'String', 'Python3']
0
lexicographically-smallest-palindrome
java
java-by-shoreshan-7d7r
IntuitionApproachComplexity Time complexity: Space complexity: Code
shoreshan
NORMAL
2025-02-26T23:21:56.173821+00:00
2025-02-26T23:21:56.173821+00:00
2
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 String makeSmallestPalindrome(String s) { int i = 0; int j = s.length() - 1; char[] array = s.toCharArray(); while(i < j) { if (array[i] != array[j]) { char minChar = array[i] < array[j] ? array[i] : array[j]; array[i] = minChar; array[j] = minChar; } i++; j--; } return new String(array); } } ```
0
0
['Java']
0
lexicographically-smallest-palindrome
100% easy solution
100-easy-solution-by-abhinav_gupta0007-8hf8
IntuitionApproachComplexity Time complexity: Space complexity: Code
Abhinav_Gupta0007
NORMAL
2025-02-23T06:07:57.062052+00:00
2025-02-23T06:07:57.062052+00:00
1
false
# Intuition <!-- Describe your first thoughts on how to solve this problem. --> # Approach <!-- Describe your approach to solving the problem. --> # Complexity - Time complexity: <!-- Add your time complexity here, e.g. $$O(n)$$ --> - Space complexity: <!-- Add your space complexity here, e.g. $$O(n)$$ --> # Code ```cpp [] class Solution { public: string makeSmallestPalindrome(string s) { int n=s.size(); int start=0,end=n-1; while(start<end) { if(s[start]==s[end]) start++,end--; else if(s[start]<s[end]) { s[end]=s[start]; start++,end--; } else { s[start]=s[end]; start++,end--; } } return s; } }; ```
0
0
['C++']
0
lexicographically-smallest-palindrome
simple
simple-by-ryuji-lpde
IntuitionApproachComplexity Time complexity: Space complexity: Code
ryuji
NORMAL
2025-02-22T01:09:14.548209+00:00
2025-02-22T01:09:14.548209+00:00
1
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 ```rust [] impl Solution { pub fn make_smallest_palindrome(s: String) -> String { let mut result = s.chars().collect::<Vec<_>>(); let len = result.len(); for i in 0..(len / 2) { let t1 = result[i]; let t2 = result[len - i - 1]; if t1 == t2 { continue; } if t1 as u8 > t2 as u8 { result[i] = t2; } else { result[len - i - 1] = t1; } } result.iter().collect::<String>() } } ```
0
0
['Rust']
0
lexicographically-smallest-palindrome
Very easy to understand-Two pointers
very-easy-to-understand-two-pointers-by-yrncg
IntuitionApproachComplexity Time complexity: Space complexity: Code
lakshmikanth01
NORMAL
2025-02-21T20:15:42.548448+00:00
2025-02-21T20:15:42.548448+00:00
7
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 makeSmallestPalindrome(self, s: str) -> str: l=0 r=len(s)-1 s=list(s) while l<r: if s[l]!=s[r]: s[l]=s[r]=min(s[l],s[r]) l+=1 r-=1 return ''.join(s) ```
0
0
['Two Pointers', 'String', 'Python3']
0
lexicographically-smallest-palindrome
TRY TO YOUR BEST TO DO YOUR OWN:)
try-to-your-best-to-do-your-own-by-srina-zn11
Code
Srinath_Y
NORMAL
2025-02-20T07:39:29.399280+00:00
2025-02-20T07:39:29.399280+00:00
2
false
# Code ```python [] class Solution(object): def makeSmallestPalindrome(self, s): s=list(s) n=len(s) for i in range(n/2): if s[i]!=s[n-1-i]: if ord(s[i])<ord(s[n-1-i]): s[n-1-i]=s[i] else: s[i]=s[n-1-i] return "".join(s) ```
0
0
['String', 'Python']
0
count-number-of-nice-subarrays
[Java/C++/Python] Sliding Window, O(1) Space
javacpython-sliding-window-o1-space-by-l-6tpq
Solution 1: atMost\nHave you read this? 992. Subarrays with K Different Integers\nExactly K times = at most K times - at most K - 1 times\n\n\n# Complexity\nTim
lee215
NORMAL
2019-11-03T04:04:38.512895+00:00
2020-06-15T07:40:04.379933+00:00
92,408
false
# **Solution 1: atMost**\nHave you read this? [992. Subarrays with K Different Integers](https://leetcode.com/problems/subarrays-with-k-different-integers/discuss/523136/JavaC%2B%2BPython-Sliding-Window)\nExactly `K` times = at most `K` times - at most `K - 1` times\n<br>\n\n# **Complexity**\nTime `O(N)` for one pass\nSpace `O(1)`\n<br>\n\n**Java:**\n```java\n public int numberOfSubarrays(int[] A, int k) {\n return atMost(A, k) - atMost(A, k - 1);\n }\n\n public int atMost(int[] A, int k) {\n int res = 0, i = 0, n = A.length;\n for (int j = 0; j < n; j++) {\n k -= A[j] % 2;\n while (k < 0)\n k += A[i++] % 2;\n res += j - i + 1;\n }\n return res;\n }\n```\n\n**C++:**\n```cpp\n int numberOfSubarrays(vector<int>& A, int k) {\n return atMost(A, k) - atMost(A, k - 1);\n }\n\n int atMost(vector<int>& A, int k) {\n int res = 0, i = 0, n = A.size();\n for (int j = 0; j < n; j++) {\n k -= A[j] % 2;\n while (k < 0)\n k += A[i++] % 2;\n res += j - i + 1;\n }\n return res;\n }\n```\n\n**Python:**\n```python\n def numberOfSubarrays(self, A, k):\n def atMost(k):\n res = i = 0\n for j in xrange(len(A)):\n k -= A[j] % 2\n while k < 0:\n k += A[i] % 2\n i += 1\n res += j - i + 1\n return res\n\n return atMost(k) - atMost(k - 1)\n```\n<br><br>\n\n# Solution II: One pass\n\nActually it\'s same as three pointers.\nThough we use `count` to count the number of even numebers.\nInsprired by @yannlecun.\n\nTime `O(N)` for one pass\nSpace `O(1)`\n<br>\n\n**Java:**\n```java\n public int numberOfSubarrays(int[] A, int k) {\n int res = 0, i = 0, count = 0, n = A.length;\n for (int j = 0; j < n; j++) {\n if (A[j] % 2 == 1) {\n --k;\n count = 0;\n }\n while (k == 0) {\n k += A[i++] & 1;\n ++count;\n }\n res += count;\n }\n return res;\n }\n```\n\n**C++:**\n```cpp\n int numberOfSubarrays(vector<int>& A, int k) {\n int res = 0, i = 0, count = 0, n = A.size();\n for (int j = 0; j < n; j++) {\n if (A[j] & 1)\n --k, count = 0;\n while (k == 0)\n k += A[i++] & 1, ++count;\n res += count;\n }\n return res;\n }\n```\n\n**Python:**\n```python\n def numberOfSubarrays(self, A, k):\n i = count = res = 0\n for j in xrange(len(A)):\n if A[j] & 1:\n k -= 1\n count = 0\n while k == 0:\n k += A[i] & 1\n i += 1\n count += 1\n res += count\n return res\n```\n\n# More Similar Sliding Window Problems\nHere are some similar sliding window problems.\nAlso find more explanations.\nGood luck and have fun.\n\n\n- 1358. [Number of Substrings Containing All Three Characters](https://leetcode.com/problems/number-of-substrings-containing-all-three-characters/discuss/516977/JavaC++Python-Easy-and-Concise)\n- 1248. [Count Number of Nice Subarrays](https://leetcode.com/problems/count-number-of-nice-subarrays/discuss/419378/JavaC%2B%2BPython-Sliding-Window-atMost(K)-atMost(K-1))\n- 1234. [Replace the Substring for Balanced String](https://leetcode.com/problems/replace-the-substring-for-balanced-string/discuss/408978/javacpython-sliding-window/367697)\n- 1004. [Max Consecutive Ones III](https://leetcode.com/problems/max-consecutive-ones-iii/discuss/247564/javacpython-sliding-window/379427?page=3)\n- 930. [Binary Subarrays With Sum](https://leetcode.com/problems/binary-subarrays-with-sum/discuss/186683/)\n- 992. [Subarrays with K Different Integers](https://leetcode.com/problems/subarrays-with-k-different-integers/discuss/523136/JavaC%2B%2BPython-Sliding-Window)\n- 904. [Fruit Into Baskets](https://leetcode.com/problems/fruit-into-baskets/discuss/170740/Sliding-Window-for-K-Elements)\n- 862. [Shortest Subarray with Sum at Least K](https://leetcode.com/problems/shortest-subarray-with-sum-at-least-k/discuss/143726/C%2B%2BJavaPython-O(N)-Using-Deque)\n- 209. [Minimum Size Subarray Sum](https://leetcode.com/problems/minimum-size-subarray-sum/discuss/433123/JavaC++Python-Sliding-Window)\n<br>
590
10
[]
64
count-number-of-nice-subarrays
C++: Visual explanation. O(1) space. Two pointers
c-visual-explanation-o1-space-two-pointe-xbcd
Algorithm\nThe best way to explain this approach is to look at the example:\nLet\'s say k = 2 and we have the following array:\n\n\n\nWe only going to work with
andnik
NORMAL
2020-02-13T21:38:11.823200+00:00
2020-02-19T06:59:46.412712+00:00
25,796
false
##### Algorithm\nThe best way to explain this approach is to look at the example:\nLet\'s say **k = 2** and we have the following array:\n\n![image](https://assets.leetcode.com/users/andnik/image_1582094442.png)\n\nWe only going to work with numbers `1` and `2` because we are only interested in if number is odd or even, we don\'t care what the actual value is.\n1. Using `i` iterate over the array counting **only odd** numbers:\n\n![image](https://assets.leetcode.com/users/andnik/image_1582094637.png)\n\n2. When **odd** is equal to **k**, we can analyse our **left part** and count how many subarrays with **odd == k** we can produce.\nWe are doing it with `j` iterating until we get to **odd number**.\n\n![image](https://assets.leetcode.com/users/andnik/image_1582094795.png)\n\nWe can see that there are `3` subarrays we can produce with **odd == k**.\n\n3. Continue with `i` again. Since **odd >= k** then every next **even number** we meet is going to **double previous count**. Let\'s see:\n\n![image](https://assets.leetcode.com/users/andnik/image_1582095218.png)\n\n4. When we meet **odd number** again we need to reset `count=1` and repeat step (2) with `j` again. In our example there\'s going to be only one subarray:\n\n![image](https://assets.leetcode.com/users/andnik/image_1582095418.png)\n\n5. And finish with counting last **even number** as in step (3).\n\nSince we are reseting `count` variable to 0, we are adding sum of all subarrays in `total` variable.\n\n##### Code\n```\nclass Solution {\npublic:\n int numberOfSubarrays(vector<int>& nums, int k) {\n int j = 0, odd = 0, count = 0, total = 0;\n for (int i = 0; i < nums.size(); i++) {\n if (nums[i] & 1) {\n odd++;\n if (odd >= k) {\n count = 1;\n while (!(nums[j++] & 1)) count++;\n total += count;\n }\n } else if (odd >= k) total += count;\n }\n return total;\n }\n};\n```
455
3
['C']
33
count-number-of-nice-subarrays
Deque with Picture
deque-with-picture-by-votrubac-p9dz
Intuition\nThis is similar to 992. Subarrays with K Different Integers.\n\nWhen we find k odd numbers, we have one nice subarray, plus an additional subarray fo
votrubac
NORMAL
2019-11-03T05:38:38.885686+00:00
2022-08-04T15:58:59.519948+00:00
17,815
false
#### Intuition\nThis is similar to [992. Subarrays with K Different Integers](https://leetcode.com/problems/subarrays-with-k-different-integers/discuss/235235/C%2B%2BJava-with-picture-prefixed-sliding-window).\n\nWhen we find `k` odd numbers, we have one nice subarray, plus an additional subarray for each even number preceding the first odd number. This is also true for each even number that follows.\n\nFor example, in the picture below we found `k == 2` odd numbers at index `4`. We have 3 nice subarrays therefore: `[2, 4], [1, 4], [0, 4]`. For even number at index `5`, we also have 3 nice subarrays: `[2, 5], [1, 5], [0, 5]`. Plus 3 subarrays for index `6`.\n\nWhen we encounter `k + 1` odd number at index `7`, we need to get rid of the first odd number (at index `2`) to have exactly `k` odd numbers. So, we count nice subarrays as if the array starts at index `3`. \n\n![image](https://assets.leetcode.com/users/votrubac/image_1572762880.png)\n\n#### Approach 1: Deque\nWe do not have to use `deque`, but it makes tracking the window easier (comparing to moving pointers). Note that in Java, the deque interface does not provide a random access, so we\'ll just use `LinkedList` instead.\n\n**Java**\n```java\npublic int numberOfSubarrays(int[] nums, int k) {\n LinkedList<Integer> deq = new LinkedList();\n deq.add(-1);\n int res = 0;\n for (int i = 0; i < nums.length; ++i) {\n if (nums[i] % 2 == 1) \n deq.add(i);\n if (deq.size() > k + 1) \n deq.pop();\n if (deq.size() == k + 1) \n res += deq.get(1) - deq.get(0);\n }\n return res;\n}\n```\n**C++**\n```cpp\nint numberOfSubarrays(vector<int>& nums, int k, int res = 0) {\n deque<int> deq = { -1 };\n for (int i = 0; i < nums.size(); ++i) {\n if (nums[i] % 2)\n deq.push_back(i);\n if (deq.size() > k + 1)\n deq.pop_front();\n if (deq.size() == k + 1)\n res += deq[1] - deq[0];\n }\n return res;\n}\n```\n**Complexity Analysis**\n- Time: O(n).\n- Memory: O(k) for the deque.
210
5
['C', 'Java']
25
count-number-of-nice-subarrays
✅Beats 100% -Explained with [ Video ] -C++/Java/Python/JS -Prefix Sum -Interview Solution
beats-100-explained-with-video-cjavapyth-7ett
\n\n# YouTube Video Explanation:\n\n### To watch the video please click on "Watch On Youtube" option available the left bottom corner of the thumbnail.\n\n **I
lancertech6
NORMAL
2024-06-22T00:56:21.994495+00:00
2024-06-22T12:41:41.216007+00:00
33,583
false
![Screenshot 2024-06-22 061620.png](https://assets.leetcode.com/users/images/c80c4521-769c-4e92-be6d-d559d69b7e88_1719017662.3639119.png)\n\n# YouTube Video Explanation:\n\n### To watch the video please click on "Watch On Youtube" option available the left bottom corner of the thumbnail.\n\n<!-- **If you want a video for this question please write in the comments** -->\n\nhttps://youtu.be/fORIuIT_KDQ\n\n\n**\uD83D\uDD25 Please like, share, and subscribe to support our channel\'s mission of making complex concepts easy to understand.**\n\nSubscribe Link: https://www.youtube.com/@leetlogics/?sub_confirmation=1\n\n*Subscribe Goal: 2250 Subscribers*\n*Current Subscribers: 2197*\n\nFollow me on Instagram : https://www.instagram.com/divyansh.nishad/\n\n---\n\n# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe problem requires counting the number of continuous subarrays with exactly `k` odd numbers. To achieve this, we can use a prefix sum approach. The key idea is to keep track of the number of odd numbers encountered so far while iterating through the array, and use this information to count subarrays with the desired property efficiently.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. **Initialize Variables**:\n - `n`: Length of the input array `nums`.\n - `cnt`: An array to keep track of the count of prefix sums (number of odd numbers encountered).\n - `cnt[0]`: Set to 1 initially, since a prefix sum of 0 (no odd numbers encountered) occurs once by default.\n - `ans`: Variable to store the final result (number of nice subarrays).\n - `t`: Variable to store the current count of odd numbers while iterating through the array.\n\n2. **Iterate Through the Array**:\n - For each element `v` in `nums`, update the count of odd numbers (`t`) encountered so far. This is done by checking if `v` is odd using `v & 1`.\n - Check if there exists a prefix sum `t - k` (i.e., a previous state where there were `t - k` odd numbers). If so, add the count of such prefix sums to `ans`.\n - Increment the count of the current prefix sum (`t`) in the `cnt` array.\n\n3. **Return the Result**:\n - After iterating through the entire array, `ans` will contain the number of nice subarrays.\n\n\n# Complexity\n- **Time Complexity**: The solution iterates through the array once and performs constant time operations in each iteration. Thus, the time complexity is \\(O(n)\\), where \\(n\\) is the length of the array.\n- **Space Complexity**: The space complexity is \\(O(n)\\) due to the additional `cnt` array used to store the count of prefix sums.\n\n\n# Step by Step Explanation\n\n\n### Example\n\nLet\'s use an example to explain the approach: \n`nums = [1, 1, 2, 1, 1]`, `k = 3`\n\n| Index | `nums[i]` | Odd Count (`t`) | `cnt` Array (Updated) | `t - k` | Count of `t - k` in `cnt` | Result (`ans`) |\n|-------|-----------|-----------------|-----------------------|---------|---------------------------|----------------|\n| 0 | 1 | 1 | [1, 1, 0, 0, 0, 0] | -2 | 0 | 0 |\n| 1 | 1 | 2 | [1, 1, 1, 0, 0, 0] | -1 | 0 | 0 |\n| 2 | 2 | 2 | [1, 1, 2, 0, 0, 0] | -1 | 0 | 0 |\n| 3 | 1 | 3 | [1, 1, 2, 1, 0, 0] | 0 | 1 | 1 |\n| 4 | 1 | 4 | [1, 1, 2, 1, 1, 0] | 1 | 1 | 2 |\n\n### Steps Explained with Example\n\n1. **Initialization**:\n - `cnt = [1, 0, 0, 0, 0, 0]`\n - `ans = 0`\n - `t = 0`\n\n2. **Iteration**:\n - **Index 0**: \n - `nums[0] = 1` (odd)\n - `t = 1` (1 odd number)\n - Update `cnt`: `cnt[1] += 1` \u2192 `cnt = [1, 1, 0, 0, 0, 0]`\n - `t - k = 1 - 3 = -2` (invalid)\n - `ans = 0`\n \n - **Index 1**:\n - `nums[1] = 1` (odd)\n - `t = 2` (2 odd numbers)\n - Update `cnt`: `cnt[2] += 1` \u2192 `cnt = [1, 1, 1, 0, 0, 0]`\n - `t - k = 2 - 3 = -1` (invalid)\n - `ans = 0`\n \n - **Index 2**:\n - `nums[2] = 2` (even)\n - `t = 2` (no change in odd count)\n - Update `cnt`: `cnt[2] += 1` \u2192 `cnt = [1, 1, 2, 0, 0, 0]`\n - `t - k = 2 - 3 = -1` (invalid)\n - `ans = 0`\n \n - **Index 3**:\n - `nums[3] = 1` (odd)\n - `t = 3` (3 odd numbers)\n - Update `cnt`: `cnt[3] += 1` \u2192 `cnt = [1, 1, 2, 1, 0, 0]`\n - `t - k = 3 - 3 = 0`\n - `cnt[0] = 1` (one valid prefix sum)\n - `ans += 1` \u2192 `ans = 1`\n \n - **Index 4**:\n - `nums[4] = 1` (odd)\n - `t = 4` (4 odd numbers)\n - Update `cnt`: `cnt[4] += 1` \u2192 `cnt = [1, 1, 2, 1, 1, 0]`\n - `t - k = 4 - 3 = 1`\n - `cnt[1] = 1` (one valid prefix sum)\n - `ans += 1` \u2192 `ans = 2`\n\n### Final Answer\nThe number of nice subarrays is `2`.\n\n---\n\n\n\n# Code\n```java []\nclass Solution {\n public int numberOfSubarrays(int[] nums, int k) {\n int n = nums.length;\n int[] cnt = new int[n + 1];\n cnt[0] = 1;\n int ans = 0, t = 0;\n for (int v : nums) {\n t += v & 1;\n if (t - k >= 0) {\n ans += cnt[t - k];\n }\n cnt[t]++;\n }\n return ans;\n }\n}\n```\n```C++ []\nclass Solution {\npublic:\n int numberOfSubarrays(vector<int>& nums, int k) {\n int n = nums.size();\n vector<int> cnt(n + 1, 0);\n cnt[0] = 1;\n int ans = 0, t = 0;\n for (int v : nums) {\n t += v & 1;\n if (t - k >= 0) {\n ans += cnt[t - k];\n }\n cnt[t]++;\n }\n return ans;\n }\n};\n```\n```Python []\nclass Solution(object):\n def numberOfSubarrays(self, nums, k):\n n = len(nums)\n cnt = [0] * (n + 1)\n cnt[0] = 1\n ans = 0\n t = 0\n for v in nums:\n t += v & 1\n if t - k >= 0:\n ans += cnt[t - k]\n cnt[t] += 1\n return ans\n \n```\n```JavaScript []\nvar numberOfSubarrays = function(nums, k) {\n let n = nums.length;\n let cnt = new Array(n + 1).fill(0);\n cnt[0] = 1;\n let ans = 0, t = 0;\n for (let v of nums) {\n t += v & 1;\n if (t - k >= 0) {\n ans += cnt[t - k];\n }\n cnt[t]++;\n }\n return ans;\n};\n```\n![upvote.png](https://assets.leetcode.com/users/images/1e88c30d-1fcc-4e7c-8ef5-bc480fcc4d24_1719017644.1184938.png)\n
161
2
['Array', 'Hash Table', 'Math', 'Sliding Window', 'Python', 'C++', 'Java', 'JavaScript']
14
count-number-of-nice-subarrays
Subarray Sum Equals K
subarray-sum-equals-k-by-herbert5812-a5a7
If you transform the input array into binary, then the problem becomes the \'Subarray Sum Equals K\' problem. You can think of k odd numbers means sum of then i
herbert5812
NORMAL
2019-11-03T04:37:21.643479+00:00
2019-11-03T04:54:11.287397+00:00
10,762
false
If you transform the input array into binary, then the problem becomes the \'Subarray Sum Equals K\' problem. You can think of k odd numbers means sum of then is k.\n\n```\nclass Solution {\npublic:\n int numberOfSubarrays(vector<int>& nums, int k) {\n unordered_map<int, int> m;\n const int n = nums.size();\n int rst = 0;\n int acc = 0;\n m[0] = 1;\n for (int i = 0; i < n; ++i) {\n acc += (nums[i]%2);\n rst += m[acc-k];\n m[acc]++;\n }\n return rst;\n }\n};\n```
151
4
['C']
16
count-number-of-nice-subarrays
[Java] PrefixSum 1pass 10line 7ms
java-prefixsum-1pass-10line-7ms-by-wangy-nsuo
At index i, if current odd numbers from the beginning is M,\nand we checked there was N previous index with (M - K) oddnum, then we got N subarrays\nres += N\n\
wangyxwyx
NORMAL
2019-11-03T04:53:28.283787+00:00
2019-11-03T05:12:53.656412+00:00
6,804
false
At index i, if current odd numbers from the beginning is M,\nand we checked there was N previous index with (M - K) oddnum, then we got N subarrays\nres += N\n\n\n```\n public int numberOfSubarrays(int[] nums, int k) {\n int cur = 0, ans = 0;\n Map<Integer, Integer> map = new HashMap<>();\n map.put(0, 1);\n for (int i = 0; i < nums.length; i++) {\n cur += nums[i] % 2 == 1 ? 1 : 0;\n map.put(cur, map.getOrDefault(cur, 0) + 1);\n ans += map.getOrDefault(cur - k, 0);\n }\n return ans;\n }\n```\n\nArray version 7ms, faster then sliding window\n```\n public int numberOfSubarrays(int[] nums, int k) {\n int cur = 0, ans = 0;\n int[] visited = new int[nums.length + 1];\n visited[0] = 1;\n for (int i = 0; i < nums.length; i++) {\n cur += nums[i] % 2 == 1 ? 1 : 0;\n visited[cur] += 1;\n ans += cur >= k ? visited[cur - k] : 0;\n }\n return ans;\n }\n```
80
1
[]
11
count-number-of-nice-subarrays
[Prefix Sum & Sliding Window Tutorial] Count Number of Nice Subarrays
prefix-sum-sliding-window-tutorial-count-vll6
This post includes the solution for both using Prexis Sum and Sliding Window.\n\nTopic : Prefix Sum\n\n### Prefix Sum:\nPrefix sum, also known as cumulative su
never_get_piped
NORMAL
2024-06-22T00:20:57.777541+00:00
2024-06-27T07:11:51.997435+00:00
14,886
false
**This post includes the solution for both using Prexis Sum and Sliding Window.**\n\n**Topic** : Prefix Sum\n\n### Prefix Sum:\nPrefix sum, also known as cumulative sum, is a technique used in computer science and mathematics to efficiently calculate the sum of a sequence of numbers. The prefix sum of a sequence `a[0], a[1] ... a[n - 1]` is another sequence` s[0], s[1] ... s[n - 1]` where each element `s[i]` represent the sum of the first i elements of the original array. (ChatGPT)\n\nAn example of prefix sum array:\n`a = [1, 2, 3, 4, 5]` =>\n`s = [1, 3, 6, 10, 15]`\n\nFeel free to refer to these two tutorials on prefix sums and their applications:\n* [Subarray Sums Divisible by K](https://leetcode.com/problems/subarray-sums-divisible-by-k/solutions/5281785/prefix-sum-number-theory-hash-table-tutorial-subarray-sums-divisible-by-k/)\n* [Continuous Subarray Sum](https://leetcode.com/problems/continuous-subarray-sum/solutions/5278327/prefix-sum-number-theory-hash-table-tutorial-continuous-subarray-sum/)\n\n\n___\n\n# **Solution**:\nTo solve this problem, we may use the **prefix sum** skill.\n\nWe first take the modulus of each `nums[i]` by two for `0 <= i < len(nums)`. Odd numbers will result in `1`, while even numbers will result in `0`. The problem becomes finding the number of subarrays that sum to `k` with the modified `nums` array.\n\nWe begin by computing the prefix sum for each index `i` of the provided array `nums`. \n\nWith the given example `nums = [1, 1, 2, 1, 1]` and `k = 3`, here is the running prefix sum : `p = [1, 2, 2, 3, 4]`. \n\nNote that the sum of a subarray `nums[i] + nums[i + 1] + ... nums[j]` can be represented as `p[j] - (i > 0 ? p[i - 1] : 0)`. \n\nIf a subarray `nums[i] + nums[i + 1] + ... + nums[j]` equals k, it must satisfy:\n* `p[j] - (i > 0 ? p[i - 1] : 0) == k`\n\nWe can utilize a **Hash Table** `prefixCount` to store our prefix sums frequency, where each key represents a prefix sum value and its corresponding occurrences. Using a native array will be faster in this case because it avoids the overhead of key hashing typically required by hash tables.\n\nFor the current running `j`, we find the number of `p[i]` satisfy the above condition. We increase the answer by `prefixCounnt[p[i]]`. \nIn this context, `p[i]` is computed as `p[j] - k`, under the condition that `p[j] >= k`. We initialize `prefixCount[0]` to `1` to specifically address the scenario where `p[j]` equals `k`.\n\n\n```c++ []\nclass Solution {\npublic:\n int numberOfSubarrays(vector<int>& nums, int k) {\n for(int i = 0; i < nums.size(); i++) {\n nums[i] %= 2;\n }\n \n vector<int> prefixCounnt(nums.size() + 1);\n prefixCounnt[0] = 1;\n int s = 0, ans = 0;\n for(int i = 0; i < nums.size(); i++) {\n s += nums[i];\n ans += (s >= k) ? prefixCounnt[s - k] : 0;\n prefixCounnt[s]++;\n }\n return ans;\n }\n};\n```\n```java []\nclass Solution {\n public int numberOfSubarrays(int[] nums, int k) {\n for (int i = 0; i < nums.length; i++) {\n nums[i] %= 2;\n }\n \n int[] prefixCount = new int[nums.length + 1];\n prefixCount[0] = 1;\n int s = 0;\n int ans = 0;\n \n for (int num : nums) {\n s += num;\n if (s >= k) {\n ans += prefixCount[s - k];\n }\n prefixCount[s]++;\n }\n \n return ans;\n }\n}\n```\n```python []\nclass Solution:\n def numberOfSubarrays(self, nums: List[int], k: int) -> int:\n for i in range(len(nums)):\n nums[i] %= 2\n \n prefix_count = [0] * (len(nums) + 1)\n prefix_count[0] = 1\n s = 0\n ans = 0\n \n for num in nums:\n s += num\n if s >= k:\n ans += prefix_count[s - k]\n prefix_count[s] += 1\n \n return ans\n```\n```Go []\nfunc numberOfSubarrays(nums []int, k int) int {\n for i := 0; i < len(nums); i++ {\n nums[i] %= 2\n }\n \n prefixCount := make([]int, len(nums)+1)\n prefixCount[0] = 1\n s := 0\n ans := 0\n \n for _, num := range nums {\n s += num\n if s >= k {\n ans += prefixCount[s-k]\n }\n prefixCount[s]++\n }\n \n return ans\n}\n```\n```PHP []\nclass Solution {\n\n /**\n * @param Integer[] $nums\n * @param Integer $k\n * @return Integer\n */\n function numberOfSubarrays($nums, $k) {\n foreach ($nums as $key => $value) {\n $nums[$key] %= 2;\n }\n \n $prefixCount = array_fill(0, count($nums) + 1, 0);\n $prefixCount[0] = 1;\n $s = 0;\n $ans = 0;\n \n foreach ($nums as $num) {\n $s += $num;\n if ($s >= $k) {\n $ans += $prefixCount[$s - $k];\n }\n $prefixCount[$s]++;\n }\n \n return $ans;\n }\n}\n```\n```javascript []\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar numberOfSubarrays = function(nums, k) {\n for (let i = 0; i < nums.length; i++) {\n nums[i] %= 2;\n }\n \n let prefixCount = new Array(nums.length + 1).fill(0);\n prefixCount[0] = 1;\n let s = 0;\n let ans = 0;\n \n for (let num of nums) {\n s += num;\n if (s >= k) {\n ans += prefixCount[s - k];\n }\n prefixCount[s]++;\n }\n \n return ans;\n};\n```\n\n\n**Complexity:**\n* Time Complexity : `O(n)`.\n* Space Complexity : `O(n)`.\n\n<br/><br/>\n___\n\n\n**Topic** : Sliding Window\nSliding Window problems are problems in which a fixed or variable-size window is moved through a data structure, typically an array or string, to solve problems efficiently based on continuous subsets of elements. This technique is used when we need to find subarrays or substrings according to a given set of conditions. (GFG Reference)\n\nThere are two types of sliding window:\n- Fixed Size Sliding Window\n- Dynamic Size Sliding Window\n\n___\n\n## Dynamic Size Sliding Window\nA **Dynamic Size Sliding Window** refers to a window or subarray whose size is not fixed; instead, it dynamically expands or shrinks based on whether it meets specified conditions.\n\n## Intuition Behind Dynamic Size Sliding Window\nGenerally, questions involving sliding window techniques often inquire about the number of subarrays or substrings that satisfy specific conditions.\n\nBy using brute force, we enumerate all subarrays or substrings and check whether each satisfies the condition. This enumeration typically results in at least `O(n^2)` time complexity.\n\nFor a fixed variable L, we check all subarrays [L : R] where L \u2264 R. The sliding window technique can be applied when all subarrays [L : M] satisfy the condition, and all subarrays with a left bound \'L\' and any right bound [M + 1 : R] fail the condition.\n\nLet\'s assume our current window has the range `[L : R]`. If the subarray `[L : R + 1]` satisfies the condition, we can continue expanding the right pointer `R` to find the maximum `M` for the current fixed `L`. If `[L : R + 1]` fails the condition, there is no need to check `[L : R + n]` because all subsequent subarrays will also fail the condition. Now it is time to expand the left pointer.\n\n## Solution\nFirst, it\'s essential to determine whether the sliding window technique is applicable. This method is suitable when:\n```\nFor a fixed variable L, we check all subarrays [L : R] where L \u2264 R. The sliding window technique can be applied when all subarrays [L : M] satisfy the condition, and all subarrays with a left bound \'L\' and any right bound [M + 1 : R] fail the condition.\n```\nThis question satisfies these criteria, making it suitable for applying the sliding window technique. How? \n\n```\nThe number of subarrays with exactly `k` odd numbers equals the count of \nsubarrays with at most `k` odd numbers minus the count of subarrays with at most `k - 1` odd numbers.\n```\n\nWe can define an `atMost(k)` function to determine the number of subarrays that have at most `k` odd numbers. We initialized a left pointer `j` and a right pointer `i`, with `i` continuously moving to the right until the condition fails. We use `s` to count the number of odd numbers within our window. If `s > k`, it indicates that the window fails the condition, prompting us to move the left pointer and update `s` accordingly. \n\nAt the same time, for the window `[j : i]` with the fixed right pointer `i`, there are `i - j + 1` subarrays that satisfy the condition.\n\n\n\n<br/><br/>\n\n\n```c++ []\nclass Solution {\npublic:\n int numberOfSubarrays(vector<int>& nums, int k) {\n return atMost(nums, k) - atMost(nums, k - 1); \n }\n \n int atMost(vector<int>& nums, int k) {\n int s = 0, ans = 0;\n for(int i = 0, j = 0; i < nums.size(); i++) {\n s += nums[i] % 2;\n while(s > k) s -= (nums[j++] % 2);\n ans += (i - j + 1);\n }\n return ans;\n }\n};\n```\n```java []\nclass Solution {\n public int numberOfSubarrays(int[] nums, int k) {\n return atMost(nums, k) - atMost(nums, k - 1);\n }\n \n private int atMost(int[] nums, int k) {\n int s = 0, ans = 0;\n for (int i = 0, j = 0; i < nums.length; i++) {\n s += nums[i] % 2;\n while (s > k) {\n s -= nums[j++] % 2;\n }\n ans += (i - j + 1);\n }\n return ans;\n }\n}\n```\n```python []\nclass Solution:\n def numberOfSubarrays(self, nums: List[int], k: int) -> int:\n return self.atMost(nums, k) - self.atMost(nums, k - 1)\n \n def atMost(self, nums: List[int], k: int) -> int:\n s, ans = 0, 0\n j = 0\n for i in range(len(nums)):\n s += nums[i] % 2\n while s > k:\n s -= nums[j] % 2\n j += 1\n ans += (i - j + 1)\n return ans\n```\n```Go []\nfunc atMost(nums []int, k int) int {\n s, ans := 0, 0\n j := 0\n for i := 0; i < len(nums); i++ {\n s += nums[i] % 2\n for s > k {\n s -= nums[j] % 2\n j++\n }\n ans += (i - j + 1)\n }\n return ans\n}\n\nfunc numberOfSubarrays(nums []int, k int) int {\n return atMost(nums, k) - atMost(nums, k-1)\n}\n```\n```PHP []\nclass Solution {\n\n /**\n * @param Integer[] $nums\n * @param Integer $k\n * @return Integer\n */\n function atMost($nums, $k) {\n $s = 0;\n $ans = 0;\n $j = 0;\n for ($i = 0; $i < count($nums); $i++) {\n $s += $nums[$i] % 2;\n while ($s > $k) {\n $s -= $nums[$j++] % 2;\n }\n $ans += ($i - $j + 1);\n }\n return $ans;\n }\n \n function numberOfSubarrays($nums, $k) {\n return $this->atMost($nums, $k) - $this->atMost($nums, $k - 1);\n }\n}\n```\n```javascript []\n/**\n * @param {number[]} nums\n * @param {number} k\n * @return {number}\n */\nvar numberOfSubarrays = function(nums, k) {\n function atMost(nums, k) {\n let s = 0, ans = 0;\n let j = 0;\n for (let i = 0; i < nums.length; i++) {\n s += nums[i] % 2;\n while (s > k) {\n s -= nums[j++] % 2;\n }\n ans += (i - j + 1);\n }\n return ans;\n }\n \n return atMost(nums, k) - atMost(nums, k - 1);\n};\n```\n\n\n**Complexity**:\n* Time Complexity : `O(n)`\n* Space Complexity : `O(1)`\n\n\n\n**Feel free to leave a comment if something is confusing, or if you have any suggestions on how I can improve the post.**
53
1
['Array', 'Hash Table', 'C', 'PHP', 'Prefix Sum', 'Java', 'Go', 'Python3', 'JavaScript']
15
count-number-of-nice-subarrays
[Java/Python 3] 1 pass Sliding Window O(n) time O(1) space w/ brief explanation.
javapython-3-1-pass-sliding-window-on-ti-sy4m
Whenever the count of odd numbers reach k, for each high boundary of the sliding window, we have indexOfLeftMostOddInWin - lowBound options for the low boundary
rock
NORMAL
2019-11-03T04:01:23.903614+00:00
2020-10-17T12:33:12.091462+00:00
7,952
false
1. Whenever the count of odd numbers reach `k`, for each high boundary of the sliding window, we have `indexOfLeftMostOddInWin - lowBound` options for the low boundary, where `indexOfLeftMostOddInWin` is the index of the leftmost odd number within the window, and `lowBound` is the index of the low boundary exclusively;\n2. Whenever the count of odd numbers more than `k`, shrink the low boundary so that the count back to `k`;\n```java\n public int numberOfSubarrays(int[] nums, int k) {\n int ans = 0, indexOfLeftMostOddInWin = 0, lowBound = -1;\n for (int num : nums) {\n k -= num % 2;\n if (nums[indexOfLeftMostOddInWin] % 2 == 0) // move to the index of first odd.\n ++indexOfLeftMostOddInWin;\n if (k < 0) { // more than k odds in window, need to shrink from low bound.\n lowBound = indexOfLeftMostOddInWin; // update the low bound value.\n }\n while (k < 0) {\n k += nums[++indexOfLeftMostOddInWin] % 2; // move to the index of next odd.\n }\n if (k == 0) { // accumulated k odd numbers in window.\n ans += indexOfLeftMostOddInWin - lowBound; // update result.\n }\n }\n return ans;\n }\n```\n```python\n def numberOfSubarrays(self, nums: List[int], k: int) -> int:\n low_bound, index_of_left_most_odd_in_win, ans = -1, 0, 0\n for num in nums:\n k -= num % 2\n if nums[index_of_left_most_odd_in_win] % 2 == 0:\n index_of_left_most_odd_in_win += 1\n if k < 0:\n low_bound = index_of_left_most_odd_in_win\n while k < 0: \n index_of_left_most_odd_in_win += 1\n k += nums[index_of_left_most_odd_in_win] % 2\n if k == 0:\n ans += index_of_left_most_odd_in_win - low_bound\n return ans\n```
48
4
[]
10
count-number-of-nice-subarrays
Python - Two pointer
python-two-pointer-by-harshhx-kyjr
\nclass Solution:\n def numberOfSubarrays(self, nums: List[int], k: int) -> int:\n right ,left = 0,0\n ans = 0 \n odd_cnt = 0\n a
harshhx
NORMAL
2021-06-11T19:01:12.047999+00:00
2021-06-11T19:01:12.048029+00:00
5,163
false
```\nclass Solution:\n def numberOfSubarrays(self, nums: List[int], k: int) -> int:\n right ,left = 0,0\n ans = 0 \n odd_cnt = 0\n ans = 0\n cur_sub_cnt = 0\n for right in range(len(nums)):\n \n if nums[right]%2 == 1:\n odd_cnt += 1\n cur_sub_cnt = 0\n \n while odd_cnt == k:\n if nums[left]%2 == 1:\n odd_cnt -= 1\n cur_sub_cnt += 1\n left += 1\n \n ans += cur_sub_cnt\n \n return ans \n```
41
0
['Two Pointers', 'Python', 'Python3']
9
count-number-of-nice-subarrays
easy peasy python solution with explanation
easy-peasy-python-solution-with-explanat-x0e6
\t# Just keep count of the current odd number.\n\t# Look in the dictionary if we can find (currendOds - k), \n\t# if it exisits that means I can get an subarray
lostworld21
NORMAL
2019-11-03T18:31:51.327405+00:00
2019-11-04T15:36:06.568313+00:00
5,465
false
\t# Just keep count of the current odd number.\n\t# Look in the dictionary if we can find (currendOds - k), \n\t# if it exisits that means I can get an subarray with k odds.\n\t# Also keep count of number of different types of odds too,\n\t# because for K =1 , [2,2,1] is a valid list, so does, [2,1] and [1].\n\t\n def numberOfSubarrays(self, nums: List[int], k: int) -> int:\n\t\t\tdic = { 0: 1 }\n\t\t\tcnt = res = 0\n\t\t\tfor idx, num in enumerate(nums):\n\t\t\t\tif num % 2 == 1:\n\t\t\t\t\tcnt += 1\n\n\t\t\t\tif cnt - k in dic:\n\t\t\t\t\tres += dic[cnt-k]\n\n\t\t\t\tdic[cnt] = dic.get(cnt, 0) + 1\n\n\t\t\treturn res
36
1
['Python', 'Python3']
8
count-number-of-nice-subarrays
C++ || Two Pointers || Clean Code
c-two-pointers-clean-code-by-jennifer-kf21
\nclass Solution {\npublic:\n int numberOfSubarrays(vector<int>& nums, int k) {\n int n = nums.size();\n int ans = 0,odd = 0,cnt = 0;\n
Jennifer__
NORMAL
2022-08-25T10:50:59.088068+00:00
2022-08-25T10:50:59.088100+00:00
4,258
false
```\nclass Solution {\npublic:\n int numberOfSubarrays(vector<int>& nums, int k) {\n int n = nums.size();\n int ans = 0,odd = 0,cnt = 0;\n int l = 0,r = 0;\n while(r<n)\n {\n if(nums[r]%2 != 0)\n {\n odd++;\n cnt = 0;\n }\n while(odd == k)\n {\n ++cnt;\n odd -= nums[l++]&1; \n }\n ans += cnt;\n r++;\n }\n return ans;\n }\n};\n```\n# If you find my solution useful , then kindly upvote it.
32
0
['Two Pointers', 'C', 'Sliding Window']
3
count-number-of-nice-subarrays
JAVA | Sliding Window
java-sliding-window-by-aman0786khan-2dt8
\nclass Solution {\n public int numberOfSubarrays(int[] nums, int k) {\n int oddcount=0;\n int res=0;\n int i=0;\n int count=0;\n
aman0786khan
NORMAL
2021-07-04T10:09:41.445090+00:00
2021-07-04T10:09:41.445122+00:00
2,351
false
```\nclass Solution {\n public int numberOfSubarrays(int[] nums, int k) {\n int oddcount=0;\n int res=0;\n int i=0;\n int count=0;\n for(int j=0;j<nums.length;j++){\n if(nums[j]%2==1){\n oddcount++;\n count=0;\n }\n while(oddcount==k){\n if(nums[i++]%2==1) oddcount--;\n count++;\n }\n res+=count;\n }\n return res;\n }\n}\n```
30
0
[]
4
count-number-of-nice-subarrays
java || sliding window || two pinter
java-sliding-window-two-pinter-by-ankurj-3bhh
\nclass Solution {\n public int numberOfSubarrays(int[] nums, int k) {\n int i=0;\n int j=0;\n int oddCount=0;\n int count=0;\n
ANKURJANA-1
NORMAL
2022-08-29T13:06:11.568062+00:00
2022-08-29T13:06:11.568103+00:00
4,309
false
```\nclass Solution {\n public int numberOfSubarrays(int[] nums, int k) {\n int i=0;\n int j=0;\n int oddCount=0;\n int count=0;\n int temp=0;\n \n while(j<nums.length){\n if(nums[j]%2==1){\n oddCount++;\n temp=0;\n }\n while(oddCount==k){\n temp++;\n if(nums[i]%2==1){\n oddCount--;\n }\n i++;\n }\n count+=temp;\n j++;\n }\n return count;\n }\n}\n```
27
0
['Sliding Window', 'Java']
6
count-number-of-nice-subarrays
Prefix sum+Sliding window vs at most k odds||35ms Beats 99.99%
prefix-sumsliding-window-vs-at-most-k-od-bz7i
Intuition\n Describe your first thoughts on how to solve this problem. \nThe concept is to use sliding window. With the help of prefix sum, it made an acceptibl
anwendeng
NORMAL
2024-06-22T02:09:04.411473+00:00
2024-06-22T06:00:05.777780+00:00
4,366
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe concept is to use sliding window. With the help of prefix sum, it made an acceptible solution.\n\n2nd approach usse at most k odds argument which is applied to solve the hard question [992. Subarrays with K Different Integers](https://leetcode.com/problems/subarrays-with-k-different-integers/solutions/4944461/sliding-window-count-subarrays-with-at-most-k-distinct-elements-15ms-beats-99-87/)\n\n3rd C++ is a variant for 1st solution without using prefix sum& a 1 pass solution.\n\nTo make an acceptible solution on weekend is not so comfortable, Some one hates me so strong & downvoted to minus. Why? [see this post](https://leetcode.com/problems/count-number-of-nice-subarrays/solutions/5349423/prefix-sum-sliding-window-vs-at-most-k-odds-35ms-beats-99-99/) \n\n****I never downvote others, try always keeping my mind peaceful to answer the comments from others & not criticize others.****\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Build an 1-indexed prefix sum array `cntOdds` for counting odd numbers in subarrays `nums[0:i]`\n2. Use sliding window pattern to solve like the following. It\'s to see that `cntOdds(nums[l..r])` can be easily computed by using prefix sums\n```\nfor (r=0, l=0; r < n; r++) {\n // Ensure the current window [l, r] has at least k odd numbers\n while (l<=r and cntOdds(nums[l..r]) > k) \n l++;\n\n // If the current window [l, r] has exactly k odd numbers\n if (cntOdds(nums[l..r]) == k) {\n l0 = l;\n // Count nice subarrays ending at r\n while (l0 <= r && cntOdds(nums[l0..r]) == k) {\n cnt++;\n l0++;\n }\n }\n}\n```\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n$$O(n)$$\n# Code Prefix sum+Sliding window||C++ 35ms Beats 99.99%\n```\nclass Solution {\npublic:\n static int numberOfSubarrays(vector<int>& nums, int k) {\n const int n = nums.size();\n vector<int> cntOdds(n+1, 0); // 1-indexed prefix sum count of odds\n\n // Create the prefix sum array\n for (int i = 0; i < n; i++) \n cntOdds[i+1] = cntOdds[i] + (nums[i] & 1);\n\n int l=0, cnt=0;\n for (int r=0; r < n; r++) {\n // Ensure the current window [l, r] has at least k odd numbers\n while (l<=r && cntOdds[r+1] - cntOdds[l] > k) \n l++;\n\n // If the current window [l, r] has exactly k odd numbers\n if (cntOdds[r+1]-cntOdds[l] == k) {\n int l0 = l;\n // Count nice subarrays ending at r\n while (l0 <= r && cntOdds[r+1]-cntOdds[l0] == k) {\n cnt++;\n l0++;\n }\n }\n }\n return cnt;\n }\n};\n\nauto init = []() {\n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n\n```\n# Solution using at most k odds\n\nThe solution is a slight modifition for [992. Subarrays with K Different Integers](https://leetcode.com/problems/subarrays-with-k-different-integers/solutions/4944461/sliding-window-count-subarrays-with-at-most-k-distinct-elements-15ms-beats-99-87/) \ncount subarrays with at most K odd elements. it makes problem much easier!\n[Please turn on English subtitles if necessary]\n[https://youtu.be/Z113uN6sKDc?si=QvC_REca7V0vt6tW](https://youtu.be/Z113uN6sKDc?si=QvC_REca7V0vt6tW)\nThe following questions can be solved sliding window:\n[713. Subarray Product Less Than K](https://leetcode.com/problems/subarray-product-less-than-k/solutions/4930759/2c-sliding-windows30ms-beats-9992/)\n[2302. Count Subarrays With Score Less Than K](https://leetcode.com/problems/count-subarrays-with-score-less-than-k/solutions/4932340/sliding-windows-like-leetcode-713-44ms-beats-100/)\n[2958. Length of Longest Subarray With at Most K Frequency](https://leetcode.com/problems/length-of-longest-subarray-with-at-most-k-frequency/solutions/4935191/sliding-window-hash-map128ms-beats-9978/)\n[2962. Count Subarrays Where Max Element Appears at Least K Times\n](https://leetcode.com/problems/count-subarrays-where-max-element-appears-at-least-k-times/solutions/4939830/sliding-window-vs-combinatorical-formula-59ms-beats-100/)\n\n\nThese problems can be solved by the following pattern:\n```\nfor(int l,r=0; r<n; r++){\n do_something_by_adding(nums[r]);\n while (!check_condition(k)){\n do_something_by_removing(nums[l]);\n l++;\n }\n update_the_answer();\n}\n```\n# C++ code\n```\nclass Solution {\npublic:\n int n;\n\n // Helper function to count subarrays with at most k odd numbers\n int niceLessEqualK(vector<int>& nums, int k){\n int odds=0, cnt=0;\n for(int l=0, r=0; r<n; r++){\n int x=nums[r];\n odds+=(x&1);\n while(odds>k){\n int y=nums[l];\n odds-=(y&1);\n l++;\n }\n cnt+=(r-l+1); // # of subarrays ending at r with at most k odd numbers\n }\n return cnt;\n }\n\n int numberOfSubarrays(vector<int>& nums, int k) {\n n = nums.size();\n return niceLessEqualK(nums, k)-niceLessEqualK(nums, k-1);\n }\n};\n\n\nauto init = []() {\n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n```\n# 3rd C++ sliding window with space O(1) & 1 pass solution\n```\nclass Solution {\npublic:\n static int numberOfSubarrays(vector<int>& nums, int k) {\n const int n = nums.size();\n\n int l=0, cnt=0, odds=0;\n for (int r=0; r < n; r++) {\n odds+=(nums[r]&1);\n // Ensure the current window [l, r] has at least k odd numbers\n while (l<=r && odds > k){\n odds-=(nums[l]&1);\n l++;\n }\n // If the current window [l, r] has exactly k odd numbers\n if (odds== k) {\n int l0 = l;\n // Count nice subarrays ending at r\n while (l0 <= r && (nums[l0]&1)==0) \n l0++;\n cnt+=l0-l+1;\n }\n }\n return cnt;\n }\n};\n\nauto init = []() {\n ios::sync_with_stdio(0);\n cin.tie(0);\n cout.tie(0);\n return \'c\';\n}();\n```
26
5
['Array', 'Sliding Window', 'Prefix Sum', 'C++']
5
count-number-of-nice-subarrays
Detailed Explanation | One Pass, O(1) Space - C++, Python, Java
detailed-explanation-one-pass-o1-space-c-odm5
Approach\n Describe your approach to solving the problem. \nOur goal is to count the number of sub arrays that have exactly k odd numbers. Let\'s take a look at
not_yl3
NORMAL
2024-06-22T00:31:44.387493+00:00
2024-06-22T02:18:27.734937+00:00
6,024
false
# Approach\n<!-- Describe your approach to solving the problem. -->\nOur goal is to count the number of sub arrays that have exactly `k` odd numbers. Let\'s take a look at Example 3 where `k = 2` (but I added an extra 1 to the end):\n\n`nums = [2,2,2,1,2,2,1,2,2,2,1]`\n\nOur first nice subarray starts at index 7 since we would have found a sub array with exactly two odd numbers. Furthermore, every subarray starting from index 0 to index 3 and ending at index 7 is also considered nice. Couynting this would be easy as we would just need to decrease our window from the left and count how many times we still have our two odd numbers.\n\nHowever, if you notice, all the sub arrays starting from index 0 (the initial start of our left pointer) up to the 1 at the end of the array, are also considered good subarrays, since we would still have a total of two odd numbers, so we also need to count these. Ending at index 7 we have 4 nice subarrays, and for every even number after index 7, we have the possibility of 4 new nice sub arrays. Therefore, if we want to calculate the amount of nice subarrays, we can repeatedly add the size of the window starting from `l` to the beginning of the first odd number for the current window (which we start to count when we reach a window that has `k` odd numbers).\n\nEverytime we find an odd number, we reset count, because we only count subarrays with exactly `k` odd numbers and since we only increment count when k reaches 0, we get to include all the even numbers that would count as nice subarrays, after we find `k` odd numbers. When we reach to the final 1 at index 10, we decrease our window and count the elements between index 4 and index 6 and add it to our result. With this method, we can effectively count the subarrays that are between the new window containing `k` odd numbers.\n# Complexity\n- Time complexity: $$O(n)$$\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity: $$O(1)$$\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```C++ []\nclass Solution {\npublic:\n int numberOfSubarrays(vector<int>& nums, int k) {\n int res = 0, count = 0;\n for (int l = 0, r = 0; r < nums.size(); r++){\n if (nums[r] % 2){\n k--;\n count = 0;\n }\n while (k == 0){\n count++;\n k += (nums[l++] % 2);\n }\n res += count;\n }\n return res;\n }\n};\n```\n```python []\nclass Solution:\n def numberOfSubarrays(self, nums: List[int], k: int) -> int:\n res = count = l = 0\n for r in range(len(nums)):\n if nums[r] % 2:\n k -= 1\n count = 0\n while not k:\n k += (nums[l] % 2)\n count += 1\n l += 1\n res += count\n return res\n```\n```Java []\nclass Solution {\n public int numberOfSubarrays(int[] nums, int k) {\n int res = 0, count = 0;\n for (int l = 0, r = 0; r < nums.length; r++){\n if (nums[r] % 2 == 1){\n k--;\n count = 0;\n }\n while (k == 0){\n count++;\n k += (nums[l++] % 2);\n }\n res += count;\n }\n return res;\n }\n}\n```\n
26
0
['Array', 'Math', 'C', 'Sliding Window', 'C++', 'Java', 'Python3']
7
count-number-of-nice-subarrays
C++ || 3 APPROACHES || SOLUTION
c-3-approaches-solution-by-_himanshu_12-b977
\nclass Solution {\npublic:\n int numberOfSubarrays(vector<int>& nums, int k) {\n int i=0;\n int j=0;\n int count=0;\n int result
_himanshu_12
NORMAL
2022-09-11T06:48:10.429934+00:00
2022-09-11T06:48:10.429968+00:00
5,382
false
```\nclass Solution {\npublic:\n int numberOfSubarrays(vector<int>& nums, int k) {\n int i=0;\n int j=0;\n int count=0;\n int result=0;\n int first_occur=0;\n vector<int>occur(nums.size(),0);\n int index=0;\n int current=0;\n // Variable window size problem\n while(j<nums.size())\n {\n // Do pre-calculation\n if(nums[j]%2!=0)\n {count++;\n occur[index++]=j;}\n // Play with condition\n if(count<k)\n j++;\n else\n {\n while(count>k)\n {\n // remove calculation for i\n if(nums[i]%2!=0)\n {count--;current++;}\n i++;\n }\n \n // Store result\n result+=occur[current]+1-i;\n j++;\n }\n \n \n }\n return result;\n }\n};\n\nTime Complexity: O(n)\nSpace Complexity: O(n)\n```\n\n```\nclass Solution {\npublic:\n int numberOfSubarrays(vector<int>& nums, int k) {\n // Replace all odd with 1 and even with 0\n for(auto &num:nums)\n if(num%2)\n num=1;\n else\n num=0;\n \n // Now find the subarray with sum at most k and k-1\n return atMost(nums,k)-atMost(nums,k-1);\n }\n int atMost(vector<int>&nums,int k)\n {\n int i=0;\n int j=0;\n int result=0;\n int sum=0;\n // Variable size window problem\n while(j<nums.size())\n {\n // Do pre-calculation\n sum+=nums[j];\n \n \n while(sum>k)\n {\n // remove calculation for i\n sum-=nums[i];\n i++;\n }\n // store result\n result+=j-i+1;\n j++;\n \n }\n return result;\n }\n};\n\nTime Complexity: O(3*n)\nSpace Complexity: O(1)\n```\n\n```\nclass Solution {\npublic:\n int numberOfSubarrays(vector<int>& nums, int k) {\n unordered_map<int,int>mp;\n // Replace odd with 1 and even with 0\n for(auto &num:nums)\n if(num%2)\n num=1;\n else \n num=0;\n mp[0]=1;\n int sum=0;\n int count=0;\n for(auto num:nums)\n {\n sum+=num;\n count+=mp[sum-k];\n mp[sum]++;\n }\n return count;\n }\n \n};\n\nTime Complexity: O(2*n)\nSpace Complexity: O(n)\n```\n\n***PLEASE UPVOTE IF YOU FIND IT A LITTLE BIT HELPFUL, MEANS A LOT ;)***
26
2
['C', 'Sliding Window', 'Prefix Sum', 'C++']
5
count-number-of-nice-subarrays
C++| 🚀 ✅ Sliding Window | 🚀 ✅ With Explaination | 🚀 ✅ Easy to Understand
c-sliding-window-with-explaination-easy-kuve5
Intuition:\r\nThe problem requires finding the number of subarrays having exactly k odd integers. We can solve the problem using sliding window technique where
devanshupatel
NORMAL
2023-04-11T15:12:40.847989+00:00
2023-04-14T14:15:44.875906+00:00
6,576
false
# Intuition:\r\nThe problem requires finding the number of subarrays having exactly k odd integers. We can solve the problem using sliding window technique where we maintain a window of contiguous subarray and slide it from left to right. While sliding the window, we keep track of the number of odd integers inside the window and count the number of subarrays having exactly k odd integers.\r\n\r\n# Approach:\r\nWe initialize two pointers, start and end, to the first element of the array. We also initialize count to zero and ans to zero. We then traverse the array using the end pointer and for each element, we increment count if it is odd. We then slide the window to the right until count becomes equal to k. At each step, we update ans with the number of subarrays having exactly k odd integers. Finally, we return ans.\r\n\r\nTo find the number of subarrays having exactly k odd integers, we subtract the number of subarrays having less than k odd integers from the number of subarrays having at most k-1 odd integers. We can reuse the same subArray function to compute both.\r\n\r\n# Complexity:\r\n- Time complexity: O(n), where n is the size of the array. We traverse the array only once.\r\n- Space complexity: O(1), as we use constant extra space.\r\n\r\n# Code\r\n```\r\nclass Solution {\r\npublic:\r\n int subArray(vector<int>& nums, int k) {\r\n int count = 0, ans = 0, start = 0, end = 0;\r\n int n = nums.size();\r\n while(end<n){\r\n if(nums[end]%2==1){\r\n count++;\r\n }\r\n while(count>k){\r\n if(nums[start]%2==1){\r\n count--;\r\n }\r\n start++;\r\n }\r\n ans += end-start+1;\r\n end++;\r\n }\r\n return ans;\r\n }\r\n int numberOfSubarrays(vector<int>& nums, int k) {\r\n return subArray(nums, k) - subArray(nums, k - 1);\r\n }\r\n};\r\n```
24
0
['Sliding Window', 'C++']
4
count-number-of-nice-subarrays
Easy C++ Solution || T.C = O(N) || Sliding Window
easy-c-solution-tc-on-sliding-window-by-k1yie
Intuition\r\nTo solve the problem of counting the number of subarrays with exactly k odd numbers, we can use a sliding window approach. This method allows us to
kumar_kshitij
NORMAL
2024-06-22T00:07:55.227272+00:00
2024-06-22T00:07:55.227288+00:00
5,418
false
# Intuition\r\nTo solve the problem of counting the number of subarrays with exactly `k` odd numbers, we can use a sliding window approach. This method allows us to efficiently manage the window of elements in the array and count the number of valid subarrays without needing to recompute for each possible subarray.\r\n\r\n# Approach\r\n1. **Initialize Variables**:\r\n - `ansCnt` to store the final count of subarrays.\r\n - `cnt` to store the count of valid subarrays ending at the current position.\r\n - Two pointers `i` and `j` to maintain the sliding window.\r\n\r\n2. **Sliding Window Expansion**:\r\n - Iterate over the array using the `j` pointer.\r\n - If the current element is odd, decrement `k` and reset `cnt` to 0.\r\n \r\n3. **Sliding Window Contraction**:\r\n - When `k` becomes 0, start contracting the window from the left (`i` pointer).\r\n - For each element removed from the window, increment `cnt`.\r\n - If the removed element is odd, increment `k` to continue expanding the window.\r\n\r\n4. **Counting Valid Subarrays**:\r\n - Add `cnt` to `ansCnt` after each expansion step to count all valid subarrays ending at position `j`.\r\n\r\n5. **Return Result**:\r\n - Return `ansCnt` as the final result.\r\n\r\n# Complexity\r\n- **Time Complexity**: $$O(n)$$, where `n` is the length of the array. Each element is processed at most twice (once by `j` and once by `i`).\r\n- **Space Complexity**: $$O(1)$$, as no extra space proportional to the input size is used.\r\n\r\n# Code\r\n```cpp\r\nclass Solution {\r\npublic:\r\n int numberOfSubarrays(vector<int>& nums, int k) {\r\n int ansCnt = 0; // Final count of subarrays\r\n int cnt = 0; // Count of valid subarrays ending at current position\r\n int i = 0, j = 0; // Two pointers for the sliding window\r\n\r\n while (j < nums.size()) {\r\n if (nums[j] % 2 != 0) { // If the current element is odd\r\n k--; // Decrement k as we have encountered an odd number\r\n cnt = 0; // Reset the count of valid subarrays ending at this position\r\n }\r\n \r\n while (k == 0) { // While we have exactly k odd numbers in the window\r\n if (nums[i] % 2 != 0) { // If the leftmost element of the window is odd\r\n k++; // Increment k as we will remove this odd number\r\n }\r\n cnt++; // Increment count of valid subarrays ending at current position\r\n i++; // Move the left pointer of the window to the right\r\n }\r\n \r\n ansCnt += cnt; // Add the count of valid subarrays to the final answer\r\n j++; // Move the right pointer of the window to the right\r\n }\r\n\r\n return ansCnt; // Return the final count of subarrays with exactly k odd numbers\r\n }\r\n};\r\n```\r\n
21
0
['Sliding Window', 'C++']
6
count-number-of-nice-subarrays
C++ Sliding Window Solution O(1) Space
c-sliding-window-solution-o1-space-by-ro-oj38
Similar to https://leetcode.com/problems/subarrays-with-k-different-integers/\n\npublic:\n int numarr(vector<int>&nums,int k){\n int ans=0;\n i
rom111
NORMAL
2020-09-02T09:28:59.954373+00:00
2020-09-02T09:28:59.954413+00:00
3,036
false
Similar to https://leetcode.com/problems/subarrays-with-k-different-integers/\n```\npublic:\n int numarr(vector<int>&nums,int k){\n int ans=0;\n int count=0;\n int i=0,j=0,n=nums.size();\n while(j<n){\n if(nums[j]%2==1){\n count++;\n }\n if(count>k){\n while(i<=j && count>k){\n if(nums[i]%2==1){\n count--;\n }\n i++;\n }\n }\n ans+=(j-i+1);\n j++;\n }\n return ans;\n }\n int numberOfSubarrays(vector<int>& nums, int k) {\n return numarr(nums,k)-numarr(nums,k-1);\n }\n};\n```
21
1
[]
2
count-number-of-nice-subarrays
nice subarrays || c++ || easy
nice-subarrays-c-easy-by-sheetaljoshi-nkhd
//exactly similar to the problem:subarrays sum equal to given sum(k)\n// we just need to convert odds with 1 and even with 0\n//and find the given sub arrays ha
sheetaljoshi
NORMAL
2021-11-28T06:52:27.358079+00:00
2021-11-28T07:23:36.312548+00:00
2,051
false
//exactly similar to the problem:subarrays sum equal to given sum(k)\n// we just need to convert odds with 1 and even with 0\n//and find the given sub arrays having sum k\nUPVOTE IF YOU GET:)\n```\nclass Solution {\npublic:\n \n int numberOfSubarrays(vector<int>& a, int k) {\n int ans=0,sum=0,n=a.size();\n map<int,int>mp;\n mp[0]=1;\n for(int i=0;i<n;i++){\n sum+=a[i]%2; // converting even with 0 & odd wiht 1;\n if(mp.find(sum-k)!=mp.end())\n ans+=mp[sum-k];\n mp[sum]++;\n }\n return ans;\n }\n};\n\n```
17
1
['C', 'C++']
4
count-number-of-nice-subarrays
C++ Prefix State Map / Two Pointers / Sliding Window
c-prefix-state-map-two-pointers-sliding-31ara
See my latest update in repo LeetCode\n\n## Solution 1. Prefix State Map\n\nUse a map m to store the mapping from the count of odd numbers cnt to the first inde
lzl124631x
NORMAL
2021-10-11T04:34:14.057512+00:00
2021-10-11T04:34:14.057565+00:00
2,491
false
See my latest update in repo [LeetCode](https://github.com/lzl124631x/LeetCode)\n\n## Solution 1. Prefix State Map\n\nUse a map `m` to store the mapping from the count of odd numbers `cnt` to the first index in the array that has `cnt` numbers in front of it and including itself.\n\nWhen `cnt >= k`, we add `m[cnt - k + 1] - m[cnt - k]` to the answer.\n\n```cpp\n// OJ: https://leetcode.com/problems/count-number-of-nice-subarrays/\n// Author: github.com/lzl124631x\n// Time: O(N)\n// Space: O(N)\nclass Solution {\npublic:\n int numberOfSubarrays(vector<int>& A, int k) {\n int N = A.size(), cnt = 0, ans = 0;\n unordered_map<int, int> m{{0,-1}};\n for (int i = 0; i < N; ++i) {\n cnt += A[i] % 2;\n if (m.count(cnt) == 0) m[cnt] = i;\n if (cnt >= k) ans += m[cnt - k + 1] - m[cnt - k]; \n }\n return ans;\n }\n};\n```\n\n## Solution 2. Two Pointers\n\nAssume the current pointer is `j` and the corresponding odd number count is `cj`, we need two pointers to get the answer.\n\nThe first pointer `i` is the index whose corresponding odd number count is `cj - k + 1`.\n\nThe second pointer `prev` is the index whose corresponding odd number count is `cj - k`.\n\nSo when `cj >= k`, we add `i - prev` to the answer.\n\n```cpp\n// OJ: https://leetcode.com/problems/count-number-of-nice-subarrays/\n// Author: github.com/lzl124631x\n// Time: O(N)\n// Space: O(1)\nclass Solution {\npublic:\n int numberOfSubarrays(vector<int>& A, int k) {\n int N = A.size(), i = 0, j = 0, prev = -1, ans = 0, ci = 0, cj = 0;\n while (j < N) {\n cj += A[j++] % 2;\n if (ci <= cj - k) {\n prev = i;\n while (ci <= cj - k) ci += A[i++] % 2;\n }\n if (cj >= k) ans += i - prev;\n }\n return ans;\n }\n};\n```\n\nOr use a single count.\n\n```cpp\n// OJ: https://leetcode.com/problems/count-number-of-nice-subarrays/\n// Author: github.com/lzl124631x\n// Time: O(N)\n// Space: O(1)\nclass Solution {\npublic:\n int numberOfSubarrays(vector<int>& A, int k) {\n int N = A.size(), i = 0, j = 0, prev = -1, ans = 0, cnt = 0;\n while (j < N) {\n int c = A[j++] % 2;\n cnt += c;\n if (c && cnt >= k) {\n prev = i;\n while (A[i] % 2 == 0) ++i;\n ++i;\n }\n if (cnt >= k) ans += i - prev;\n }\n return ans;\n }\n};\n```\n\n## Solution 3. AtMost to Equal\n\nCheck out "[C++ Maximum Sliding Window Cheatsheet Template!](https://leetcode.com/problems/frequency-of-the-most-frequent-element/discuss/1175088/C%2B%2B-Maximum-Sliding-Window-Cheatsheet-Template!)"\n\nExactly `k` times = At Most `k` times - At Most `k - 1` times.\n\n```cpp\n// OJ: https://leetcode.com/problems/count-number-of-nice-subarrays/\n// Author: github.com/lzl124631x\n// Time: O(N)\n// Space: O(1)\n// Ref: https://leetcode.com/problems/count-number-of-nice-subarrays/discuss/419378/JavaC%2B%2BPython-Sliding-Window-O(1)-Space\nclass Solution {\n int atMost(vector<int> &A, int k) {\n int N = A.size(), i = 0, ans = 0;\n for (int j = 0; j < N; ++j) {\n k -= A[j] % 2;\n while (k < 0) k += A[i++] % 2;\n ans += j - i;\n }\n return ans;\n }\npublic:\n int numberOfSubarrays(vector<int>& A, int k) {\n return atMost(A, k) - atMost(A, k - 1);\n }\n};\n```
17
0
[]
1
count-number-of-nice-subarrays
Python Solution Prefix Sum
python-solution-prefix-sum-by-yuyingji-xy2h
\ndef numberOfSubarrays(self, nums, k):\n """\n :type nums: List[int]\n :type k: int\n :rtype: int\n """\n res = 0\n
yuyingji
NORMAL
2019-11-03T04:03:16.509603+00:00
2019-11-03T18:38:39.962951+00:00
3,257
false
```\ndef numberOfSubarrays(self, nums, k):\n """\n :type nums: List[int]\n :type k: int\n :rtype: int\n """\n res = 0\n count = 0\n prefix = {}\n prefix[0] = 1\n for i in range(len(nums)):\n \n if nums[i] % 2 != 0:\n count += 1\n if count in prefix:\n prefix[count] += 1\n else: \n prefix[count] = 1\n\t"""the key of prefix represent the number of odd number untill certain position, the value represent the number of positions"""\n \n for c in prefix:\n if c - k in prefix:\n res += prefix[c] *prefix[c - k]\n return res\n ```
17
2
[]
7
count-number-of-nice-subarrays
💹Easy 3 Approaches 🔰📊|| Beats 98% || 🚀 Hashing and Two Pointers 🎯|| In Depth
easy-3-approaches-beats-98-hashing-and-t-mf1e
\r\n# Intuition:\r\nThe problem is essentially about finding subarrays with exactly \'k\' odd numbers. \r\nWe can use a hashmap to count the occurrences of pref
laggerk
NORMAL
2024-06-22T07:13:49.400576+00:00
2024-06-22T07:13:49.400621+00:00
2,836
false
\r\n# Intuition:\r\nThe problem is essentially about finding subarrays with exactly \'k\' odd numbers. \r\nWe can use a hashmap to count the occurrences of prefix sums, which helps us keep track \r\nof the number of odd numbers encountered so far.\r\n \r\n# Approach 1:\r\n1. Initialize a hashmap to store the count of prefix sums.\r\n2. Traverse the array and for each element, check if it\'s odd. If it is, increment the current sum.\r\n3. Calculate the difference between the current sum and \'k\'.\r\n4. Check if this difference exists in the hashmap, which means there\'s a subarray with exactly \'k\' odd numbers.\r\n5. Update the hashmap with the current sum.\r\n6. Return the total count of such subarrays.\r\n \r\n# Complexity:\r\n1. Time complexity: O(n), where \'n\' is the length of the input array.\r\n2. Space complexity: O(n), for the hashmap used to store the prefix sums.\r\n\r\n\r\n```JAVA []\r\nclass Solution {\r\n public int numberOfSubarrays(int[] nums, int k) {\r\n int n = nums.length; // Get the length of the input array\r\n HashMap<Integer, Integer> mpp = new HashMap<>(); // Initialize hashmap to store prefix sums\r\n int sum = 0; // Initialize sum to count odd numbers\r\n int ans = 0; // Initialize answer to count subarrays with exactly \'k\' odd numbers\r\n mpp.put(0, 1); // Initialize hashmap with 0 sum to handle cases where subarray starts from index 0\r\n\r\n for (int i = 0; i < n; i++) { // Iterate through the array\r\n if (nums[i] % 2 == 1) { // Check if the current number is odd\r\n sum += 1; // Increment the sum if the number is odd\r\n }\r\n int diff = sum - k; // Calculate the difference needed to form a subarray with \'k\' odd numbers\r\n ans += mpp.getOrDefault(diff, 0); // Add the count of subarrays found with the required difference\r\n mpp.put(sum, mpp.getOrDefault(sum, 0) + 1); // Update the hashmap with the current sum\r\n }\r\n return ans; // Return the total count of subarrays with exactly \'k\' odd numbers\r\n }\r\n}\r\n```\r\n```C++ []\r\n#include <vector>\r\n#include <unordered_map>\r\n\r\nusing namespace std;\r\n\r\nclass Solution {\r\npublic:\r\n int numberOfSubarrays(vector<int>& nums, int k) {\r\n int n = nums.size(); // Get the size of the input array\r\n unordered_map<int, int> mpp; // Initialize unordered_map to store prefix sums\r\n int sum = 0; // Initialize sum to count odd numbers\r\n int ans = 0; // Initialize answer to count subarrays with exactly \'k\' odd numbers\r\n mpp[0] = 1; // Initialize map with 0 sum to handle cases where subarray starts from index 0\r\n\r\n for (int i = 0; i < n; ++i) { // Iterate through the array\r\n if (nums[i] % 2 == 1) { // Check if the current number is odd\r\n sum += 1; // Increment the sum if the number is odd\r\n }\r\n int diff = sum - k; // Calculate the difference needed to form a subarray with \'k\' odd numbers\r\n ans += mpp[diff]; // Add the count of subarrays found with the required difference\r\n mpp[sum]++; // Update the map with the current sum\r\n }\r\n return ans; // Return the total count of subarrays with exactly \'k\' odd numbers\r\n }\r\n};\r\n\r\n```\r\n```Python []\r\nclass Solution:\r\n def numberOfSubarrays(self, nums: list[int], k: int) -> int:\r\n n = len(nums) # Get the length of the input array\r\n mpp = {0: 1} # Initialize dictionary to store prefix sums\r\n sum = 0 # Initialize sum to count odd numbers\r\n ans = 0 # Initialize answer to count subarrays with exactly \'k\' odd numbers\r\n\r\n for num in nums: # Iterate through the array\r\n if num % 2 == 1: # Check if the current number is odd\r\n sum += 1 # Increment the sum if the number is odd\r\n diff = sum - k # Calculate the difference needed to form a subarray with \'k\' odd numbers\r\n ans += mpp.get(diff, 0) # Add the count of subarrays found with the required difference\r\n mpp[sum] = mpp.get(sum, 0) + 1 # Update the dictionary with the current sum\r\n\r\n return ans # Return the total count of subarrays with exactly \'k\' odd numbers\r\n\r\n```\r\n\r\n# Intuition\r\n<!-- Describe your first thoughts on how to solve this problem. -->\r\nTo find the number of subarrays with exactly \'k\' odd numbers, we can utilize a sliding window approach combined with prefix sum logic. By counting the number of subarrays with up to \'k\' odd numbers and subtracting the count of subarrays with up to \'k-1\' odd numbers, we can derive the result.\r\n\r\n# Approach 2 \r\n<!-- Describe your approach to solving the problem. -->\r\n1. Implement a helper function `countLessThanEqualToK` that returns the number of subarrays with at most \'k\' odd numbers.\r\n2. The main function will use this helper to calculate the difference between the number of subarrays with at most \'k\' odd numbers and the number of subarrays with at most \'k-1\' odd numbers, giving the result.\r\n3. Use two pointers to maintain a sliding window and keep track of the number of odd numbers in the current window.\r\n4. Expand the window to include new elements and shrink it when the count of odd numbers exceeds \'k\'.\r\n\r\n# Complexity\r\n- Time complexity: $$O(n)$$, where \'n\' is the length of the input array, as each element is processed at most twice (once when expanding and once when contracting the window).\r\n\r\n- Space complexity: $$O(1)$$, as we only use a few extra variables and do not use additional space proportional to the input size.\r\n\r\n```JAVA []\r\n\r\nclass Solution {\r\n public int numberOfSubarrays(int[] nums, int k) {\r\n return countLessThanEqualToK(nums, k) - countLessThanEqualToK(nums, k - 1);\r\n }\r\n\r\n public int countLessThanEqualToK(int[] nums, int k) {\r\n int i = 0; // Left pointer of the sliding window\r\n int count = 0; // Count of valid subarrays\r\n int oddCount = 0; // Number of odd elements in the current window\r\n \r\n for (int j = 0; j < nums.length; j++) { // Right pointer of the sliding window\r\n if (nums[j] % 2 == 1) // Check if the current element is odd\r\n oddCount++; // Increment the odd count\r\n \r\n // While the number of odd elements exceeds \'k\', move the left pointer to the right\r\n while (oddCount > k) {\r\n if (nums[i] % 2 == 1) // Check if the element at the left pointer is odd\r\n oddCount--; // Decrement the odd count\r\n i++; // Move the left pointer to the right\r\n } \r\n \r\n count += j - i + 1; // Add the number of valid subarrays ending at \'j\'\r\n }\r\n \r\n return count; // Return the total count of subarrays with at most \'k\' odd numbers\r\n }\r\n}\r\n```\r\n```C++ []\r\n#include <vector>\r\nusing namespace std;\r\n\r\nclass Solution {\r\npublic:\r\n int numberOfSubarrays(vector<int>& nums, int k) {\r\n return countLessThanEqualToK(nums, k) - countLessThanEqualToK(nums, k - 1);\r\n }\r\n\r\n int countLessThanEqualToK(vector<int>& nums, int k) {\r\n int i = 0; // Left pointer of the sliding window\r\n int count = 0; // Count of valid subarrays\r\n int oddCount = 0; // Number of odd elements in the current window\r\n \r\n for (int j = 0; j < nums.size(); ++j) { // Right pointer of the sliding window\r\n if (nums[j] % 2 == 1) // Check if the current element is odd\r\n oddCount++; // Increment the odd count\r\n \r\n // While the number of odd elements exceeds \'k\', move the left pointer to the right\r\n while (oddCount > k) {\r\n if (nums[i] % 2 == 1) // Check if the element at the left pointer is odd\r\n oddCount--; // Decrement the odd count\r\n i++; // Move the left pointer to the right\r\n } \r\n \r\n count += j - i + 1; // Add the number of valid subarrays ending at \'j\'\r\n }\r\n \r\n return count; // Return the total count of subarrays with at most \'k\' odd numbers\r\n }\r\n};\r\n```\r\n```Python []\r\nclass Solution:\r\n def numberOfSubarrays(self, nums: list[int], k: int) -> int:\r\n return self.countLessThanEqualToK(nums, k) - self.countLessThanEqualToK(nums, k - 1)\r\n\r\n def countLessThanEqualToK(self, nums: list[int], k: int) -> int:\r\n i = 0 # Left pointer of the sliding window\r\n count = 0 # Count of valid subarrays\r\n oddCount = 0 # Number of odd elements in the current window\r\n \r\n for j in range(len(nums)): # Right pointer of the sliding window\r\n if nums[j] % 2 == 1: # Check if the current element is odd\r\n oddCount += 1 # Increment the odd count\r\n \r\n # While the number of odd elements exceeds \'k\', move the left pointer to the right\r\n while oddCount > k:\r\n if nums[i] % 2 == 1: # Check if the element at the left pointer is odd\r\n oddCount -= 1 # Decrement the odd count\r\n i += 1 # Move the left pointer to the right\r\n \r\n count += j - i + 1 # Add the number of valid subarrays ending at \'j\'\r\n \r\n return count # Return the total count of subarrays with at most \'k\' odd numbers\r\n```\r\n\r\n# Intuition\r\n<!-- Describe your first thoughts on how to solve this problem. -->\r\nThe problem requires finding subarrays with exactly `k` odd numbers. A useful technique for such problems is the sliding window approach, combined with prefix sums to count the number of valid subarrays.\r\n\r\n# Approach 3\r\n<!-- Describe your approach to solving the problem. -->\r\n1. Initialize an array `map` to keep track of the count of subarrays ending at a specific index with a specific number of odd numbers.\r\n2. Traverse through the array and count the number of odd numbers encountered so far.\r\n3. For each element, calculate the difference between the current count of odd numbers and `k`. This difference tells us how many times we have encountered a prefix with exactly `k` odd numbers.\r\n4. Update the result by adding the count from the `map` for this difference.\r\n5. Finally, update the `map` to include the current count of odd numbers.\r\n\r\n# Complexity\r\n- Time complexity:\r\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\r\n$$O(n)$$ - We traverse the array once.\r\n\r\n- Space complexity:\r\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\r\n$$O(n)$$ - We use an auxiliary array to store counts.\r\n\r\n```JAVA []\r\nclass Solution {\r\n public int numberOfSubarrays(int[] nums, int k) {\r\n int n = nums.length;\r\n int[] map = new int[n + 1]; // create map to store odd count digits\r\n map[0] = 1; // initialize map[0] for subarrays that exactly match the count k\r\n int count = 0; // count of odd numbers so far\r\n int ans = 0; // result to store the number of valid subarrays\r\n for (int j = 0; j < n; j++) {\r\n if (nums[j] % 2 == 1) // check if the current number is odd\r\n count++;\r\n int diff = count - k; // calculate the difference between count and k\r\n if (diff >= 0) // if the difference is non-negative, we have valid subarrays\r\n ans += map[diff]; // add the count of such subarrays to the result\r\n map[count]++; // update the map with the current count of odd numbers\r\n }\r\n return ans; // return the final count of valid subarrays\r\n }\r\n}\r\n```C++ []\r\nclass Solution {\r\npublic:\r\n int numberOfSubarrays(vector<int>& nums, int k) {\r\n int n = nums.size();\r\n vector<int> map(n + 1, 0); // create map to store odd count digits\r\n map[0] = 1; // initialize map[0] for subarrays that exactly match the count k\r\n int count = 0; // count of odd numbers so far\r\n int ans = 0; // result to store the number of valid subarrays\r\n for (int j = 0; j < n; j++) {\r\n if (nums[j] % 2 == 1) // check if the current number is odd\r\n count++;\r\n int diff = count - k; // calculate the difference between count and k\r\n if (diff >= 0) // if the difference is non-negative, we have valid subarrays\r\n ans += map[diff]; // add the count of such subarrays to the result\r\n map[count]++; // update the map with the current count of odd numbers\r\n }\r\n return ans; // return the final count of valid subarrays\r\n }\r\n};\r\n\r\n```\r\n```Python []\r\nclass Solution:\r\n def numberOfSubarrays(self, nums: List[int], k: int) -> int:\r\n n = len(nums)\r\n map = [0] * (n + 1) # create map to store odd count digits\r\n map[0] = 1 # initialize map[0] for subarrays that exactly match the count k\r\n count = 0 # count of odd numbers so far\r\n ans = 0 # result to store the number of valid subarrays\r\n for num in nums:\r\n if num % 2 == 1: # check if the current number is odd\r\n count += 1\r\n diff = count - k # calculate the difference between count and k\r\n if diff >= 0: # if the difference is non-negative, we have valid subarrays\r\n ans += map[diff] # add the count of such subarrays to the result\r\n map[count] += 1 # update the map with the current count of odd numbers\r\n return ans # return the final count of valid subarrays\r\n\r\n```\r\nPlease UPVote for Anya Chan if you read it till here !!!\r\n![image.png](https://assets.leetcode.com/users/images/1e9043c0-9547-4fd7-80e2-bbc09a47537d_1719040415.06887.png)\r\n\r\n\r\n\r\n
16
1
['Array', 'Hash Table', 'Math', 'Sliding Window', 'Python', 'C++', 'Java', 'Python3']
3
count-number-of-nice-subarrays
JAVA || Picture + Detail Explanation || prefix sum + HashMap || Easy Solution
java-picture-detail-explanation-prefix-s-gpyl
\n\n In this problem , First we will change the odd digit from 1 and even with zero in given array.\n then we use the same approach which we used in the leetcod
ayushx
NORMAL
2021-10-20T20:45:56.983692+00:00
2021-11-02T18:23:57.601451+00:00
2,988
false
![image](https://assets.leetcode.com/users/images/27b0cd6e-ffd3-4eca-8787-6b8d0b15b43f_1634763142.2267573.png)\n\n* In this problem , First we will change the odd digit from 1 and even with zero in given array.\n* then we use the same approach which we used in the leetcode problem 560. If you want detail explanation then ->\nHere is the link of the problem \n[https://leetcode.com/problems/subarray-sum-equals-k/discuss/1532102/java-picture-explanation-2-methods-prefix-sum-hashmap-easy-solution]\n\n```\n public int numberOfSubarrays(int[] nums, int k) {\n \n int s=0,e=nums.length;\n \n for(int i=0;i<e;i++){\n if(nums[i]%2!=0){\n nums[i]=1;\n }else{\n nums[i]=0;\n }\n }\n \n Map<Integer,Integer> p = new HashMap();\n \n p.put(0,1); \nint ans=0,sum=0;\n \n for(int i=0;i<nums.length;i++){\n sum+=nums[i];\n if(p.containsKey(sum-k)){\n ans+=p.get(sum-k);\n } \n p.put(sum,p.getOrDefault(sum,0)+1);\n } \n return ans; \n \n }\n```\n\nif you like it , then please upvote it
15
2
['Sliding Window', 'Prefix Sum', 'Java']
5
count-number-of-nice-subarrays
Java Solution
java-solution-by-credit_card-lcab
Replace all odd numbers with 1 and even with zeroes\n\nNow the problem becomes\nhttps://leetcode.com/problems/subarray-sum-equals-k/\n\nFind number of sub arrys
credit_card
NORMAL
2020-09-06T14:15:24.362308+00:00
2020-10-04T14:53:12.707737+00:00
1,295
false
Replace all odd numbers with 1 and even with zeroes\n\nNow the problem becomes\n[https://leetcode.com/problems/subarray-sum-equals-k/](https://leetcode.com/problems/subarray-sum-equals-k/)\n\nFind number of sub arrys with sum = K\n```\npublic int numberOfSubarrays(int[] nums, int k) {\n //Replace all odd by 1 and even by 0\n for(int i=0;i<nums.length;i++){\n nums[i] = (nums[i] %2 == 0) ? 0 : 1;\n }\n \n //problem becomes number of subarrays with sum = k\n HashMap<Integer,Integer> map = new HashMap<>();\n int res = 0;\n int sum = 0;//cumulative sum\n map.put(0,1);\n for(int i=0;i<nums.length;i++){\n sum+=nums[i];\n if(map.containsKey(sum - k)){\n res+=map.get(sum - k);\n }\n map.put(sum,map.getOrDefault(sum,0)+1);\n }\n return res;\n }\n```
15
0
[]
3
count-number-of-nice-subarrays
✅ One Line Solution
one-line-solution-by-mikposp-gv5a
(Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly)Code #1.1 - One LineTime complexity: O(n). Space com
MikPosp
NORMAL
2024-06-22T09:18:33.601994+00:00
2025-02-11T10:52:26.574263+00:00
1,323
false
(Disclaimer: this is not an example to follow in a real project - it is written for fun and training mostly) # Code #1.1 - One Line Time complexity: $$O(n)$$. Space complexity: $$O(n)$$. ``` class Solution: def numberOfSubarrays(self, a: List[int], k: int) -> int: return (z:=Counter([q:=0])) and sum(z.update([q:=q+v%2]) or z[q-k] for v in a) ``` # Code #1.2 - Unwrapped ``` class Solution: def numberOfSubarrays(self, a: List[int], k: int) -> int: res, z, q = 0, Counter([0]), 0 for v in a: q += v%2 z[q] += 1 result += z[q-k] return res ``` (Disclaimer 2: code above is just a product of fantasy packed into one line, it is not claimed to be 'true' oneliners - please, remind about drawbacks only if you know how to make it better)
14
0
['Array', 'Hash Table', 'Math', 'Prefix Sum', 'Python', 'Python3']
1
count-number-of-nice-subarrays
Sliding window
sliding-window-by-anil-budamakuntla-kvga
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
ANIL-BUDAMAKUNTLA
NORMAL
2024-06-22T00:33:52.290783+00:00
2024-06-22T00:33:52.290808+00:00
1,237
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:o(n)\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:o(1)\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n int numberOfSubarrays(vector<int>& nums, int k) {\n\n int i = 0, a = -1, b = -1, n = nums.size(), cnt = 0, ans = 0;\n\n // First, find the first window that contains exactly k odd numbers\n while (cnt < k && i < n) {\n if (nums[i] % 2 == 1) { // Check if the number is odd\n cnt++; // Increment the odd count\n if (b == -1) // Set the initial right boundary\n b = i;\n }\n i++;\n }\n\n // If there are not enough odd numbers to make a window of k odd numbers\n if (cnt < k)\n return 0;\n \n // Calculate the number of subarrays for the initial window\n ans = b - a;\n\n // Continue iterating through the rest of the array\n while (i < n) {\n if (nums[i] % 2 == 1) { // Check if the current number is odd\n a = b; // Move the left boundary to the previous right boundary\n b++;\n while (b < n) {\n if (nums[b] % 2 == 1) // Find the next odd number\n break;\n b++;\n }\n }\n ans += b - a; // Add the number of valid subarrays ending at the current position\n i++;\n }\n return ans; // Return the total number of valid subarrays\n }\n};\n```\n![image.png](https://assets.leetcode.com/users/images/187f2c1a-ca96-48ce-8818-bfb0c10e4ac3_1719016399.1251187.png)\n
14
0
['Array', 'Sliding Window', 'C++']
5
count-number-of-nice-subarrays
C++ Sliding Window Solution + Probability Rule O(N)
c-sliding-window-solution-probability-ru-v1vg
Runtime: 112 ms, faster than 93.17% of C++ online submissions for Count Number of Nice Subarrays.\nMemory Usage: 67.5 MB, less than 91.98% of C++ online submiss
ahsan83
NORMAL
2021-07-11T15:57:15.687238+00:00
2021-07-11T17:26:57.770515+00:00
1,880
false
Runtime: 112 ms, faster than 93.17% of C++ online submissions for Count Number of Nice Subarrays.\nMemory Usage: 67.5 MB, less than 91.98% of C++ online submissions for Count Number of Nice Subarrays.\n\n```\nInorder to solve the problem we can easily find the main subarray containing K odd numbers using Sliding\nWindow approach. Here main subarray means the subarray which has window such as all left most values\nof first odd number are even if possible and all right most values of last odd number are even if possible\ncause there can be exactly K odd numbers and this main subarray will get the subarrays where all odd\nnumbers of the window wil be present. So, we expand window in each step and shrink window if odd count >K. \nWhen odd count == K, we have to find the main subarray and so we expand the window as long as there\nis no new odd number. Now we need the possible subarrays from this main subarray where al odd numbers\nwill be present. For calculating the number of such possible subarrays we can consider the subarry from the\nfirst to last occurence of odd number as a single number X. Then we have to count the number of even\nnumbers EL at the left of X and the number of even numbers ER at the right of X cause they will make the\npossible subarrays from main subarray. \nFor the current main subarray the possible subarray count = (EL +1) * (ER+1)\n```\n\n```\nThis equation comes from the Independent Probability Rule: P(AB) = P(A) * P(B)\nFor example given array : [a,b,c,d,e] and X = c then the number of possible subarray where X exists are,\nNo of way of taking or not taking element from the left of X = EL + 1\nNo of way of taking or not taking element from the right of X = ER + 1\nSo, total possible subarrays with element X = (EL + 1) * (ER + 1) cause here taking element from left and\nright of element X in the subarray is Independent.\nFor [a,b,c,d,e] and X = c => Subarray count = (2+1) * (2+1) = 3\n{a,b,c}, {b,c},{c}, {a,b,c,d},{b,c,d},{a,b,c,d,e},{b,c,d,e},{c,d},{c,d,e}\n\nSo using above formula we can count the total subarray from a main subarray and sum up the count of \nall main subarrays in the given array and get the result.\n\nExample Input: nums = [2,2,1,2,1,2,2,1,2,2], k = 2, Output: 15 Below is the simulation of this example\n```\n\n![image](https://assets.leetcode.com/users/images/93861dec-986d-45f7-89e8-d79b938a0c7e_1626024085.1761098.png)\n\n```\nclass Solution {\npublic:\n int numberOfSubarrays(vector<int>& nums, int k) {\n\n int n = nums.size();\n\n // total number of calid subarray\n int res = 0;\n \n // count the odd numbers in the window\n int cnt = 0;\n \n // first and last pointer of sliding window\n int i = 0;\n int j = 0;\n while(j<n)\n {\n // update count of the odd number in window\n if((nums[j++]&1)==1)cnt++; \n \n // shrink window until odd number count == k\n while(cnt>k)if((nums[i++]&1)==1)cnt--; \n \n // if odd number count == k then we found our main subarray\n if(cnt==k)\n {\n int lc = 0, rc = 0;\n \n // shrink window from left till any odd number found\n // means, count number of even number at the left of first odd number in window, EL\n while(j<n && (nums[j]&1)==0)j++,rc++;\n\n // expand window to right till any odd number found\n // means, count number of even number at the right of last odd number in window, ER\n while(i<n && (nums[i]&1)==0)i++,lc++;\n \n // based on probability formula the total possible subarray inclusing all odd numbers\n // of the main subarray window is (EL + 1) * (ER + 1)\n res+= ((lc+1) * (rc+1));\n }\n }\n \n return res;\n }\n};\n```\n\n\n
14
0
['Array', 'C', 'Sliding Window', 'Probability and Statistics']
3
count-number-of-nice-subarrays
C++ : Sliding Window || Two pointers || O(n) Space
c-sliding-window-two-pointers-on-space-b-n2j4
This question is slightly based on sliding window, however one needs proper idea of whats going on.\nWe actually just need to maintain the condition of (Oddnumb
nivedita_chatterjee_021
NORMAL
2022-02-13T14:44:46.111529+00:00
2022-02-13T14:44:46.111556+00:00
2,206
false
This question is slightly based on sliding window, however one needs proper idea of whats going on.\nWe actually just need to maintain the condition of (Oddnumbers==k), once we get it equal.\nTill the time our odd number count is less than k, we just simply keep updating **"end"**.\nOnce our oddnum count is equal to k, we start increamenting **"start"**, till the time we reach an odd number(this actually gives us the number of nice subarrays till that end point, let it be **"cnt"**).\nAfter this , we continue our quest till we get our (k+1)th odd number but before that each even number means that we again have cnt number of nice subarrays possible so we keep updating total.\nOnce we get an odd number , we increament **"start"**, reduce oddnumber count by 2(because we do not increament end , so just reducing count by 1 would lead us to take the new odd number more than once and an infinte loop would start).\nSo , like this the process continues.\n\n```\nclass Solution {\npublic:\n int numberOfSubarrays(vector<int>& nums, int k) {\n int start=0,end=0;\n int count=0, total=0, cnt=0;\n while(end<nums.size())\n {\n if(nums[end]%2!=0)\n count++;\n if(nums[end]%2==0 && count==k)\n { total+=cnt;end++;continue;}\n if(count<k)\n end++;\n else if(count==k)\n {\n while(count==k)\n {\n cnt++;\n if(nums[start]%2==0)\n {start++;continue;}\n else\n {break;}\n \n }\n total+=cnt;\n \n end++;\n }\n else if(count>k)\n {\n start++;\n cnt=0;\n count-=2;\n \n \n \n }\n \n }\n return total;\n }\n};\n\n```\nThis is the code !!\nPlease upvote if you find it even slightly helpful !! : )\n
13
0
['Two Pointers', 'C', 'Sliding Window', 'C++']
2