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
break-a-palindrome
cpp solution || 100% faster || simplest approach
cpp-solution-100-faster-simplest-approac-7rfx
Thank you for checking out the solution\nDo upvote if it helps :)\n\n__Approach :\nFirst task is to check if the string is not a single character, if it is then
TheCodeAlpha
NORMAL
2022-10-10T06:03:21.881382+00:00
2022-10-10T06:03:21.881425+00:00
503
false
__Thank you for checking out the solution\nDo upvote if it helps :)__\n\n__Approach :\nFirst task is to check if the string is not a single character, if it is then no answer exists\nAfter this one important fact is to be used, "THE GIVEN STRING IS A PALINDROME"__\n```\nThis makes the takes simpler as any character at a distance x from the beginning \nis same as the character at a distance x from the end\nWhich means we only have to traverse half of the string\n```\n__So Start the traversal, if a character at the i(th) position is not \'a\'__\n>__Check if the length is odd and i = length/2__\n>> __If yes, break the loop (Since our string is like aaaa...*...aaaa), we h=will have to replace the last \'a\' with \'b\'__\n \n>__Change the character at the position i, to \'a\', this works because the character from the end is not same as \'a\' (NOW)\n>Return the manipulated String__\n>\n__If by now, nothing has been returned, the string is either all (a)s or of type \naaaa...*...aaaa, where * can be any character other than \'a\' and the length is surely odd for the string of this type__\n\n__What to do ?\nJust change the last \'a\' of the string to \'b\' and return the string__\n\n__Below is the coding implementation for the same__\n_____\n```\nclass Solution \n// Runtime: 0 ms, faster than 100.00% of C++ online submissions for Break a Palindrome.\n{\npublic:\n string breakPalindrome(string palindrome)\n {\n ios_base::sync_with_stdio(0);\n int l = palindrome.size();\n // A single letter entry can\'t be broken in any way so that it doesnt stay a palindrome\n // Hence return ""\n if (l == 1)\n return "";\n // Now the remaining task to find a position that doesn\'t contain \'a\'\n for (int i = 0; i <= l/2; i++)\n if (palindrome[i] != \'a\')\n {\n\t\t\t //If the position lies in the center of the string, and the string has an odd-number length\n\t\t\t\t// Time to break, becoz changing it into \'a\', will create a new palindrome\n if ((l & 1) && i == l / 2)\n break;\n\t\t\t\t// Otherwise change the character at index i to \'a\', and return it\n palindrome[i] = \'a\';\n return palindrome;\n }\n // In a case where\n // We have all \'a\'s,\n // Or when replacing a char in the middle makes the string palindrome again\n // Just replace b with the character at the end\n palindrome[l - 1] = \'b\';\n return palindrome;\n }\n};\n```\n__Time Complexity : O(N/2) ~ O(N) , where N is the length of the string\nSpace Complexity : O(1)__\n\n__Some Test case to consider:\n"aaaaaaa"\n"aaabaaa"\n"aaabbaaa"\n"abccba"\n"c"\n"a"__
6
0
['C++']
2
break-a-palindrome
Simple java Traversal
simple-java-traversal-by-poorvank-8f6t
\n public String breakPalindrome(String palindrome) {\n int n = palindrome.length();\n if(n<=1) {\n return "";\n }\n i
poorvank
NORMAL
2020-01-25T16:03:35.847160+00:00
2020-01-25T16:09:58.983302+00:00
1,615
false
```\n public String breakPalindrome(String palindrome) {\n int n = palindrome.length();\n if(n<=1) {\n return "";\n }\n int i=0;\n// Keep traversing until u find a character other than \'a\'.. or if u find another character but it is in the mid of palindrome, and changing it won\'t make any difference.\n while(i<n && (palindrome.charAt(i)==\'a\' || (palindrome.charAt(i)>\'a\' && n%2!=0 && i==((n)/2)))) {\n i++;\n }\n// if i goes till n-1 i.e all characters are \'a\', replace last by b otherwise replace ith character by \'a\' \n return i<n-1?(palindrome.substring(0,i)+\'a\'+palindrome.substring(i+1)):palindrome.substring(0,n-1)+\'b\';\n }\n```
6
0
[]
2
break-a-palindrome
JavaScript - JS
javascript-js-by-mlienhart-sb7e
\n/**\n * @param {string} palindrome\n * @return {string}\n */\nvar breakPalindrome = function (palindrome) {\n let result = palindrome.split("");\n\n for (le
mlienhart
NORMAL
2021-10-16T14:05:55.012995+00:00
2023-01-06T21:16:04.516990+00:00
414
false
```\n/**\n * @param {string} palindrome\n * @return {string}\n */\nvar breakPalindrome = function (palindrome) {\n let result = palindrome.split("");\n\n for (let i = 0; i < Math.floor(result.length / 2); i++) {\n if (result[i] !== "a") {\n result[i] = "a";\n return result.join("");\n }\n }\n\n if (result.length === 1) {\n return "";\n } else {\n result[result.length - 1] = "b";\n return result.join("");\n }\n};\n```
5
0
['JavaScript']
0
break-a-palindrome
Java easy Solution || String
java-easy-solution-string-by-kadamyogesh-8z45
\nclass Solution {\n public String breakPalindrome(String palindrome) {\n int n=palindrome.length();\n if(n==1){//if length is 1\n r
kadamyogesh7218
NORMAL
2022-10-14T09:15:04.115800+00:00
2022-10-14T09:15:39.993861+00:00
1,967
false
```\nclass Solution {\n public String breakPalindrome(String palindrome) {\n int n=palindrome.length();\n if(n==1){//if length is 1\n return "";\n }\n \n for(int i=0;i<n;i++){\n \n //if char is non-\'a\' (but it should not be middle char of odd length string)\n if(palindrome.charAt(i)!=\'a\' && !(n%2!=0 && i==n/2)){\n \n //replace first non-\'a\' character with \'a\'\n palindrome=palindrome.substring(0,i)+\'a\'+palindrome.substring(i+1);\n return palindrome;\n }\n }\n \n //if string has only \'a\' change last character with b\n palindrome=palindrome.substring(0,n-1)+\'b\';\n \n return palindrome;\n }\n}\n```
4
0
['String', 'Greedy', 'Java']
1
break-a-palindrome
Easy to Understand || 100% faster || O( n ) || C++
easy-to-understand-100-faster-o-n-c-by-d-4679
\nclass Solution {\npublic:\n string breakPalindrome(string pal){\n int n = pal.size();\n if(n == 1){\n return "";\n }\n\t\t\
dero_703
NORMAL
2022-10-10T18:38:52.298248+00:00
2022-12-03T03:49:44.203170+00:00
606
false
```\nclass Solution {\npublic:\n string breakPalindrome(string pal){\n int n = pal.size();\n if(n == 1){\n return "";\n }\n\t\t\n\t\t// traverse only half of the string\n\t\t// if we find any ith character other than \'a\' make that ith character to \'a\' \n\t\t// return the string\n\t\t\n for(int i=0; i<n/2; i++){\n if(pal[i] != \'a\'){\n pal[i] = \'a\';\n return pal;\n }\n }\n\t\t\n // if all character in string are only \'a\'. \n\t\t// Ex : "aaaaa" then make the last character to \'b\' -> "aaaab"\n\t\t\n\t\tpal[n-1] = \'b\'; \n return pal;\n }\n};\n```\n: ) \uD83D\uDC4D : )
4
0
['String', 'C', 'C++']
1
break-a-palindrome
🌻Easy C++ || Faster than 100% || Intuitive || O(N) / LogN
easy-c-faster-than-100-intuitive-on-logn-g583
Please Upvote if you Like it :)\n The simple Intuition is that we have to convert the 1st non-\'a\' character to \'a\' which does not have \'a\' on its palindro
iqlipse_abhi
NORMAL
2022-10-10T04:57:01.163237+00:00
2022-10-10T04:57:34.964703+00:00
983
false
**Please Upvote if you Like it :)**\n* The simple Intuition is that we have to convert the 1st non-\'a\' character to \'a\' which does not have \'a\' on its palindrome side thats it. so that it both does not become \'a\' this is how we will be able to obtain smallest break palindrome.\n* One edge case is that what if we have string like \'\'aaaaaaaaa\'\' then we have to simply convert the last character of string to \'b\' to make it smallest i.e \'\'aaaaaaab\'\'.\n\n\n```\nclass Solution {\npublic:\n string breakPalindrome(string p) {\n int start = 0, end = p.size() - 1;\n if(p.size() <= 1) return "";\n while(start < end){\n if(p[start] != \'a\' && p[end] != \'a\'){\n p[start] = \'a\';\n return p;\n }\n else{\n start++; end--;\n }\n }\n p[p.size() - 1] = \'b\';\n return p;\n }\n};\n```
4
0
['C']
1
break-a-palindrome
🗓️ Daily LeetCoding Challenge October, Day 10
daily-leetcoding-challenge-october-day-1-weri
This problem is the Daily LeetCoding Challenge for October, Day 10. Feel free to share anything related to this problem here! You can ask questions, discuss wha
leetcode
OFFICIAL
2022-10-10T00:00:28.856160+00:00
2022-10-10T00:00:28.856234+00:00
4,827
false
This problem is the Daily LeetCoding Challenge for October, Day 10. Feel free to share anything related to this problem here! You can ask questions, discuss what you've learned from this problem, or show off how many days of streak you've made! --- If you'd like to share a detailed solution to the problem, please create a new post in the discuss section and provide - **Detailed Explanations**: Describe the algorithm you used to solve this problem. Include any insights you used to solve this problem. - **Images** that help explain the algorithm. - **Language and Code** you used to pass the problem. - **Time and Space complexity analysis**. --- **📌 Do you want to learn the problem thoroughly?** Read [**⭐ LeetCode Official Solution⭐**](https://leetcode.com/problems/break-a-palindrome/solution) to learn the 3 approaches to the problem with detailed explanations to the algorithms, codes, and complexity analysis. <details> <summary> Spoiler Alert! We'll explain this 1 approach in the official solution</summary> **Approach 1:** Greedy </details> If you're new to Daily LeetCoding Challenge, [**check out this post**](https://leetcode.com/discuss/general-discussion/655704/)! --- <br> <p align="center"> <a href="https://leetcode.com/subscribe/?ref=ex_dc" target="_blank"> <img src="https://assets.leetcode.com/static_assets/marketing/daily_leetcoding_banner.png" width="560px" /> </a> </p> <br>
4
0
[]
54
break-a-palindrome
Python easy to read and understand | greedy
python-easy-to-read-and-understand-greed-kd2t
```\nclass Solution:\n def breakPalindrome(self, s: str) -> str:\n n = len(s)\n if n == 1:\n return \'\'\n for i in range(n//
sanial2001
NORMAL
2022-08-12T10:31:43.766382+00:00
2022-08-12T10:31:43.766430+00:00
978
false
```\nclass Solution:\n def breakPalindrome(self, s: str) -> str:\n n = len(s)\n if n == 1:\n return \'\'\n for i in range(n//2):\n if s[i] != \'a\':\n return s[:i] + \'a\' + s[i+1:]\n return s[:-1] + \'b\'
4
0
['Python', 'Python3']
0
break-a-palindrome
C++ Solution
c-solution-by-saurabhvikastekam-sdsv
\nclass Solution \n{\n public:\n string breakPalindrome(string palindrome) \n {\n string res;\n if (palindrome.size() == 1)\n
SaurabhVikasTekam
NORMAL
2021-09-24T07:59:35.258202+00:00
2021-09-24T07:59:35.258234+00:00
507
false
```\nclass Solution \n{\n public:\n string breakPalindrome(string palindrome) \n {\n string res;\n if (palindrome.size() == 1)\n return res;\n for (size_t i = 0; i < palindrome.size() / 2; i++)\n {\n if(palindrome[i] != \'a\')\n {\n palindrome[i] = \'a\';\n return palindrome; \n }\n }\n palindrome[palindrome.size() - 1] = \'b\';\n return palindrome; \n }\n};\n```
4
0
['C', 'C++']
0
break-a-palindrome
Solution with pictures and notes [JavaScript]
solution-with-pictures-and-notes-javascr-6616
Algorithm\nIn a palindrome, all the characters appear in pairs except for the middle element. To generate lexicographically smallest string, we can select any c
darkalarm
NORMAL
2021-09-23T08:04:08.363656+00:00
2022-10-10T06:00:34.701114+00:00
629
false
# Algorithm\nIn a palindrome, all the characters appear in pairs except for the middle element. To generate lexicographically smallest string, we can select any character before the middle, and change it to the smallest character, i.e. `a`. So we iterate through the first half of the string. If the character isn\'t already the smallest, we change it to \'a\' and return the new string.\n\nedge case 1: if the length of the string is $1$, then we can never break the string by replacement. So we return `""`.,\n\nedge case 2: if all the characters are already the smallest, i.e. `a`, then we change the last character of the string to the second smallest character available, i.e. `b`.\n\n![break-palindrome.jpeg](https://assets.leetcode.com/users/images/350e6e3d-7044-4b9b-9fc6-e39f59136b0b_1665381611.0712337.jpeg)\n\n# Complexity\nIf there are total $n$ characters in the string -\n\n* Time complexity: $O(n)$. we iterate through the first half, or $(n / 2)$ characters to determine the first character to be replaced. Depending on the language of implementation, string mutation can be $O(1)$ or $O(n)$ operation. So the time complexity is $O(n)$.\n* Space complexity: In the current implementation, we make use of an auxiliary array to replace the corresponding character, so it requires $O(n)$ space. If the replacement is done in place though, then it wouldn\'t \nneed any extra space. (We don\'t count the space reserved only for the output)\n\n# Code\n```\n/**\n * @param {string} palindrome\n * @return {string}\n */\nfunction breakPalindrome(palindrome) {\n if (palindrome.length === 1) {\n return "";\n }\n let arr = palindrome.split("");\n for (let i = 0; i <= Math.floor(arr.length / 2) - 1; i++) {\n if (arr[i] !== \'a\') {\n arr[i] = \'a\';\n return arr.join("");\n }\n }\n arr[arr.length - 1] = \'b\';\n return arr.join("");\n};\n```
4
0
['JavaScript']
0
break-a-palindrome
[C++] Easy to Understand- Faster than 100%
c-easy-to-understand-faster-than-100-by-rit2d
```\nclass Solution {\npublic:\n string breakPalindrome(string palindrome) {\n if(palindrome.size()<=1) return "";\n int st=0;int en=palindrome.len
pratyush63
NORMAL
2020-07-31T17:38:59.463293+00:00
2020-07-31T17:38:59.463325+00:00
430
false
```\nclass Solution {\npublic:\n string breakPalindrome(string palindrome) {\n if(palindrome.size()<=1) return "";\n int st=0;int en=palindrome.length()-1;\n while(st<en)\n {\n if(palindrome[st]!=\'a\')//Change first non \'a\' to \'a\'\n {\n palindrome[st]=\'a\';\n return palindrome;\n }\n st++;\n en--;\n }\n //If no character changed yet, then change last character to \'b\'\n palindrome[palindrome.length()-1]=\'b\';\n return palindrome;\n }\n};
4
0
[]
1
break-a-palindrome
C# Solution
c-solution-by-leonhard_euler-eu17
\npublic class Solution \n{\n public string BreakPalindrome(string palindrome) \n {\n if(palindrome.Length <= 1) return "";\n var charArray
Leonhard_Euler
NORMAL
2020-01-26T03:36:36.698314+00:00
2020-01-26T03:36:36.698355+00:00
309
false
```\npublic class Solution \n{\n public string BreakPalindrome(string palindrome) \n {\n if(palindrome.Length <= 1) return "";\n var charArray = palindrome.ToCharArray();\n for(int i = 0; i < charArray.Length / 2; i++)\n {\n if(charArray[i] != \'a\')\n {\n charArray[i] = \'a\';\n return new string(charArray);\n }\n }\n \n charArray[charArray.Length - 1] = \'b\';\n return new string(charArray);\n }\n}\n```
4
0
[]
1
break-a-palindrome
Clean Python 3 three lines
clean-python-3-three-lines-by-lenchen111-w5xo
\nclass Solution:\n def breakPalindrome(self, palindrome: str) -> str:\n for i in range(len(palindrome) // 2):\n if palindrome[i] != \'a\':
lenchen1112
NORMAL
2020-01-25T16:12:18.706892+00:00
2020-01-25T16:12:57.802356+00:00
977
false
```\nclass Solution:\n def breakPalindrome(self, palindrome: str) -> str:\n for i in range(len(palindrome) // 2):\n if palindrome[i] != \'a\': return palindrome[:i] + \'a\' + palindrome[i+1:]\n return \'\' if len(palindrome) == 1 else palindrome[:-1] + \'b\'\n```
4
0
['Greedy', 'Python3']
0
break-a-palindrome
Simple solution using Java with explanation
simple-solution-using-java-with-explanat-q35i
If the sting is of length 1, return ""\nIf all the elements in the string are \'a\' then replace the last one with \'b\' else repalce the first non \'a\' member
ashish53v
NORMAL
2020-01-25T16:02:24.478434+00:00
2020-01-25T16:03:19.379715+00:00
945
false
If the sting is of length 1, return ""\nIf all the elements in the string are \'a\' then replace the last one with \'b\' else repalce the first non \'a\' member with an \'a\'\n```\nclass Solution {\n public String breakPalindrome(String palindrome) {\n String s = palindrome;\n if(s.length() == 1){\n return "";\n }\n int i = 0, j = s.length() - 1;\n char[] arr = s.toCharArray();\n while(i < j){\n if(s.charAt(j) == \'a\'){\n j--; \n i++;\n }else{\n arr[i] = \'a\';\n return new String(arr);\n }\n }\n arr[s.length() - 1] = \'b\';\n return new String(arr);\n }\n}\n```
4
0
[]
0
break-a-palindrome
beats 99% simple 4 conditions
beats-99-simple-4-conditions-by-raviteja-vlia
Intuition\n Describe your first thoughts on how to solve this problem. \nThe goal is to transform a given palindrome string into a non-palindrome string that is
raviteja_29
NORMAL
2024-07-25T14:23:02.805980+00:00
2024-07-25T14:23:02.806013+00:00
208
false
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\nThe goal is to transform a given palindrome string into a non-palindrome string that is the smallest possible in lexicographical order. Here\'s how to approach it step-by-step.\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n1. Edge Case: If the length of the palindrome is 1, return an empty string since it\'s impossible to break the palindrome.\n2. Replace First Non-\'a\' Character: Iterate through the string. For the first character that is not \'a\', replace it with \'a\'. If this transformation makes the string non-palindromic, return it immediately.\n3. Check if Result is Still a Palindrome: After replacing the first non-\'a\' character, check if the resulting string is a palindrome. If it is, continue to the next character.\n4. All Characters are \'a\': If the entire string consists of \'a\'s and replacing the first non-\'a\' character still results in a palindrome, replace the last character with \'b\' to ensure the string is non-palindromic.\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 def breakPalindrome(self, palindrome: str) -> str:\n if len(palindrome)==1:\n return ""\n else:\n for x in range(len(palindrome)):\n s = ""\n if palindrome[x]!="a":\n s+=palindrome[:x]+\'a\'+palindrome[x+1:]\n if s!=s[::-1]:\n return s\n s = palindrome[:len(palindrome)-1]+"b"\n return s\n```
3
0
['String', 'Greedy', 'Python3']
2
break-a-palindrome
STRINGS || 80% S.C || CPP
strings-80-sc-cpp-by-ganesh_ag10-mww4
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
Ganesh_ag10
NORMAL
2024-05-12T02:59:01.929088+00:00
2024-05-12T02:59:01.929107+00:00
91
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 breakPalindrome(string palindrome) {\n if(palindrome.size()==1) return "";\n for(int i=0;i<palindrome.size()/2;i++){\n if(palindrome[i]!=\'a\'){\n palindrome[i]=\'a\';\n return palindrome;\n }\n }\n palindrome[palindrome.size()-1]=\'b\';\n \n return palindrome;\n }\n};\n```
3
0
['C++']
0
break-a-palindrome
||Beats 100%|| very Easy Beginner friendly Java Solution||
beats-100-very-easy-beginner-friendly-ja-96h5
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n- first we convert Stri
ammar_saquib
NORMAL
2023-08-18T19:39:16.299216+00:00
2023-08-18T19:39:16.299236+00:00
271
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- first we convert String to a char Array\n- check if length of the char Array is less than 2 then return an empty String\n- iterate upto length/2 and check whether the character at index i is not equal to \'a\' if condition satisfied then the character at that index is set to \'a\' which makes the string non palindrome and it will be lexicographically smallest and return it after converting it to string\n- if for loop ends means all the character upto length/2 is a and by changing the middle element does make it non palindrome so to make it non palindrome we make the last charcter to b which is lexicographically smaller\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 breakPalindrome(String palindrome) {\n char[] cstr=palindrome.toCharArray();\n if(cstr.length<2)\n return "";\n for(int i=0;i<cstr.length/2;i++)\n {\n if(cstr[i]!=\'a\')\n {\n cstr[i]=\'a\';\n return String.valueOf(cstr);\n }\n\n }\n\n cstr[cstr.length-1]=\'b\';\n return String.valueOf(cstr);\n }\n}\n```
3
0
['Java']
0
break-a-palindrome
C++ || fastest || O(n) || Intuitive || easy
c-fastest-on-intuitive-easy-by-anmol_pro-dc0p
O(n)\nIt is given in question that string is Palindrome and we have to remove the one character only ,so that string become non Palindromic , so that it is le
anmol_pro
NORMAL
2022-10-10T20:57:03.668073+00:00
2022-10-10T20:57:03.668108+00:00
1,585
false
O(n)\nIt is given in question that string is Palindrome and we have to remove the one character only ,so that string become non Palindromic , so that it is lexicographically smallest, first thing that comes in mind is that traverse the string and replace the character that does not equal to a, but it approach will fail for this testcase "aa" or "aaa" ,now , To handle this case we will replace last character with b ,Still our approach will fail for some case like "ab", \n\n"what we will do is that if run loop for 0 to n/2 if we find any character that does not equal to a replace and return the string other-wise replace last character with b"\n\n```\nclass Solution {\npublic:\n string breakPalindrome(string s) {\n int n = s.size(); //size of string \n if(n==1 || n==0) //return empty string if size==1 or size==0\n return "";\n \n for(int i=0; i<n/2; i++) {\n if(s[i]!=\'a\') {\n s[i] = \'a\'; // character doesnot equal to \'a\' replace it with a and return the string\n return s;\n }\n }\n \n s[n-1] = \'b\'; // change the last character with b\n return s;\n }\n};\n// why we run loop to n/2 not n because it will make Palindromic string for some cases like "aba"\n```\n
3
0
[]
1
break-a-palindrome
Python3 - O(n / 2) Time | O(n) Space | With Comments.
python3-on-2-time-on-space-with-comments-3tcm
\nclass Solution:\n\n# intuition is simple\n# the moment we encounter a character other than an \'a\', replace it with \'a\' (to make it lexographically shortes
yukkk
NORMAL
2022-10-10T18:38:35.428937+00:00
2022-10-10T18:38:52.687792+00:00
3,517
false
```\nclass Solution:\n\n# intuition is simple\n# the moment we encounter a character other than an \'a\', replace it with \'a\' (to make it lexographically shortest)\n# if we do not find any other character, it means it\'s all filled with \'a\'s\n# so the next shortest string then comes when we replace the last character with a \'b\'\n\n def breakPalindrome(self, palindrome: str) -> str:\n n = len(palindrome)\n if n == 1:\n return ""\n \n\t\t# \'flag\' to check if we encounter an \'a\'\n\t\t# also, we want to iterate through half the string, leaving the middle element if length is odd\n\t\t# in each iteration, we fill the resultant array from both the ends\n\t\t# rest is intuitive\n\t\t\n res, flag = [palindrome[n // 2]] * n, 0\n for i in range(n // 2):\n if not flag and palindrome[i] != \'a\':\n res[i] = \'a\'\n flag = 1\n else:\n res[i] = palindrome[i]\n res[n - i - 1] = palindrome[i]\n \n if not flag:\n res[-1] = "b"\n return "".join(res)\n```
3
0
[]
0
break-a-palindrome
C++ : Simple solution by only checking for 2 chars 'a', 'b'
c-simple-solution-by-only-checking-for-2-wimx
class Solution {\npublic:\n string breakPalindrome(string p) {\n int n = p.size();\n if(n==1) return "";\n for(int i = 0; i < n/2; i++){
madhavaarul
NORMAL
2022-10-10T17:57:37.574132+00:00
2022-10-10T17:58:38.536731+00:00
2,098
false
class Solution {\npublic:\n string breakPalindrome(string p) {\n int n = p.size();\n if(n==1) return "";\n for(int i = 0; i < n/2; i++){\n if (p[i]!=\'a\') {\n p[i]=\'a\';\n return p;\n }\n }\n for(int i = 0; i < n/2; i++){\n if (p[n-1-i]!=\'b\') {\n p[n-1-i]=\'b\';\n return p;\n }\n }\n return "";\n }\n};
3
0
[]
1
break-a-palindrome
Easy java solution
easy-java-solution-by-siddhant_1602-s3bn
\n# Code\n\nclass Solution {\n public String breakPalindrome(String p) {\n int k=p.length();\n if(k==1)\n return "";\n for(in
Siddhant_1602
NORMAL
2022-10-10T17:38:49.204789+00:00
2022-10-10T17:38:49.204827+00:00
54
false
\n# Code\n```\nclass Solution {\n public String breakPalindrome(String p) {\n int k=p.length();\n if(k==1)\n return "";\n for(int i=0;i<k/2;i++)\n {\n if(p.charAt(i)!=\'a\')\n {\n return p.substring(0,i)+"a"+p.substring(i+1);\n }\n }\n return p.substring(0,k-1)+"b";\n }\n}\n```
3
0
['Java']
0
break-a-palindrome
BEST/ EASIEST APPROACH
best-easiest-approach-by-prince_7672526-u3j8
Intuition if size is 1 then empty because every charcter is a palindrome . Check for half length if not found \'a\' then replace that character with \'a\' ot
prince_7672526
NORMAL
2022-10-10T16:30:45.379354+00:00
2022-10-10T16:30:45.379385+00:00
45
false
# Intuition if size is 1 then empty because every charcter is a palindrome . Check for half length if not found \'a\' then replace that character with \'a\' otherwise replace the last character with \'b\'.\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach check for a for making it lexicographically smallest if not found then replace the last character to \'b\' otherwise replace it with \'a\'.\n<!-- Describe your approach to solving the problem. -->\n\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 breakPalindrome(string palindrome) {\n int n=palindrome.size();\n if(n==1){\n return "";\n }\n bool ok=0;\n for(int i=0;i<n/2;i++){\n if(palindrome[i]!=\'a\'){\n palindrome[i]=\'a\';\n ok=1;\n break;\n }\n }\n if(!ok)palindrome[n-1]=\'b\';\n return palindrome;\n }\n};\n```
3
0
['C++']
1
break-a-palindrome
Simple python solution
simple-python-solution-by-amishah137-n1xb
\nclass Solution:\n def breakPalindrome(self, palindrome: str) -> str:\n if len(palindrome)==1:\n return \'\'\n for i in range(int(l
amishah137
NORMAL
2022-10-10T16:04:57.941867+00:00
2022-10-10T16:04:57.941905+00:00
1,890
false
```\nclass Solution:\n def breakPalindrome(self, palindrome: str) -> str:\n if len(palindrome)==1:\n return \'\'\n for i in range(int(len(palindrome)/2)):\n if palindrome[i]!=\'a\':\n palindrome= palindrome[:i]+\'a\'+palindrome[i+1:]\n return palindrome\n return palindrome[:-1]+\'b\'\n```
3
0
['Python']
0
break-a-palindrome
JS | 99% | With explanation
js-99-with-explanation-by-karina_olenina-t3ku
\n\n\nTo solve this problem, first of all we check if the length of the string is equal to 1, if it is, we return an empty string (" ").\nFor convenience, we tu
Karina_Olenina
NORMAL
2022-10-10T15:32:17.784441+00:00
2022-10-17T17:03:44.628091+00:00
763
false
![image](https://assets.leetcode.com/users/images/ffb87ca4-b84a-48c7-8998-2d0f35422d26_1665416260.8143685.png)\n\n\nTo solve this problem, first of all we check if the length of the string is equal to **1**, if it is, we return an empty string **(" ")**.\nFor convenience, we turn the string into an **array**.\nNow we do a search on the first half of the array (we add \'**~~**\' to remove the fractional part if the number is not paired), since this is a polyndrom, it makes no sense for us to sort through the second part.\nIn case we find a character that is **greater** than \'**a**\', we change it to \'**a**\'. But if the whole string consists **only** of characters equal to \'**a**\', we take the **last** **one** and change it to \'**b**\'.\nAt the end, it remains only to collect the string from the array again.\n\n```\nlet breakPalindrome = function (palindrome) {\n if (palindrome.length === 1) return \'\';\n let arr = Array.from(palindrome);\n\n for (let i = 0; i < ~~(arr.length / 2 ); i++) {\n if (arr[i] > \'a\') {\n arr[i] = \'a\';\n return arr.join(\'\');\n }\n }\n arr[arr.length - 1] = \'b\';\n return arr.join(\'\');\n};\n```\n\nI hope I was able to explain clearly.\n **Happy coding!** \uD83D\uDE43
3
0
['JavaScript']
1
break-a-palindrome
Python Solution - Stop overcomplicating it! (KISS)
python-solution-stop-overcomplicating-it-iomr
I\'ve seen so many overly complex python solutions here - figured it was time to break it down simply.\n1) If there is only one character, we cannot make it not
zathrath03
NORMAL
2022-10-10T14:30:56.501246+00:00
2022-10-10T17:27:30.639715+00:00
504
false
I\'ve seen so many overly complex python solutions here - figured it was time to break it down simply.\n1) If there is only one character, we cannot make it not a palindrome, so just return "" (the for loop is skipped since ```1 // 2``` is 0)\n2) Go through the first half of the palindrome and find the first character that is not equal to \'a\'. Using integer division ensures that we don\'t check the middle character of an odd-lengthed palindrome (since replacing the middle character would never change it into a non-palindrome).\n3) If a non-a character is found, replace it with an \'a\' and return the string\n4) Otherwise, the lexicographically smallest correction we can make is to change the last character to a \'b\' (since we already know that all other characters are \'a\'s)\n\n```\ndef breakPalindrome(self, palindrome: str) -> str:\n for i in range(len(palindrome) // 2):\n if palindrome[i] != \'a\':\n return palindrome[:i] + \'a\' + palindrome[i+1:]\n return "" if len(palindrome) == 1 else palindrome[:-1] + \'b\'\n```
3
0
['Greedy', 'Python', 'Python3']
1
break-a-palindrome
C++ || Easy 0ms Solution with explanation || Only Simulation ||
c-easy-0ms-solution-with-explanation-onl-thlw
Intuition\nAs we have to always replace with least possible character so we will only be replacing by either a or b only . Try to think why for some moment and
Khwaja_Abdul_Samad
NORMAL
2022-10-10T13:45:09.803215+00:00
2022-10-10T13:45:09.803253+00:00
896
false
# Intuition\nAs we have to always replace with least possible character so we will only be replacing by either a or b only . Try to think why for some moment and you will know the reason . \n(You may ask in comments if you dont get it).\n\n# Approach\nThe Approach is now simple we will traverse string till we dont reach mid or till we dont get other charcter than \'a\'.\nIf We stop before mid that is the character to be replacxed and replace it with a.\nElse we will replace the last character with b .\n\nFor EX : aaaaaaaaaa ,aaacaaa ,\nwill change into aaaaaaaaab, aaacaab.\n\n\n# Complexity\n- Time complexity: O(n)\n\n- Space complexity: O(1)\n\n# Code\n```\nclass Solution {\npublic:\n string breakPalindrome(string palindrome) {\n \n if(palindrome.length() == 1)\n return "";\n\n int i = 0 ; \n\n while(palindrome[i] == \'a\' && i< (palindrome.length())/2 )\n i++;\n\n if(i == (palindrome.length())/2)\n palindrome.back() = \'b\';\n else\n palindrome[i] = \'a\';\n\n return palindrome;\n \n \n }\n};\n```\n
3
0
['C++']
0
break-a-palindrome
Python Soln
python-soln-by-soumya_suman-xcan
\n\n def breakPalindrome(self, p: str) -> str:\n n=len(p)\n l=list(p)\n if n==1:\n return ""\n for i in range(n//2):\n
soumya_suman
NORMAL
2022-10-10T13:14:59.093829+00:00
2022-10-10T18:47:02.610834+00:00
983
false
```\n\n def breakPalindrome(self, p: str) -> str:\n n=len(p)\n l=list(p)\n if n==1:\n return ""\n for i in range(n//2):\n if l[i]>"a":\n l[i]="a"\n return \'\'.join(map(str, l))\n l[-1]="b"\n return \'\'.join(l)\n\t\t\n```\n***Upvote if you got help :-)***
3
0
['Python']
2
break-a-palindrome
Python Elegant & Short
python-elegant-short-by-kyrylo-ktl-skar
\nclass Solution:\n """\n Time: O(n)\n Memory: O(n)\n """\n\n def breakPalindrome(self, palindrome: str) -> str:\n if len(palindrome) ==
Kyrylo-Ktl
NORMAL
2022-10-10T10:32:34.182513+00:00
2022-10-10T10:32:34.182548+00:00
754
false
```\nclass Solution:\n """\n Time: O(n)\n Memory: O(n)\n """\n\n def breakPalindrome(self, palindrome: str) -> str:\n if len(palindrome) == 1:\n return \'\'\n\n n = len(palindrome)\n letters = list(palindrome)\n\n for i in range(n // 2):\n if letters[i] > \'a\':\n letters[i] = \'a\'\n break\n else:\n letters[-1] = \'b\'\n\n return \'\'.join(letters)\n```\n\nIf you like this solution remember to **upvote it** to let me know.\n
3
0
['Python', 'Python3']
0
break-a-palindrome
C++ || Short and simple || beats 100% || TC=O(N)
c-short-and-simple-beats-100-tcon-by-dev-m0gu
Please Upvote if you find this helpeful\n\nclass Solution {\npublic:\n string breakPalindrome(string palindrome) {\n if(palindrome.size()<=1)\n
devmehta787
NORMAL
2022-10-10T08:51:47.328653+00:00
2022-10-10T08:58:26.742447+00:00
40
false
**Please Upvote if you find this helpeful**\n```\nclass Solution {\npublic:\n string breakPalindrome(string palindrome) {\n if(palindrome.size()<=1)\n return "";\n int n=palindrome.size();\n for(int i=0; i<n/2; i++){\n if(palindrome[i]!=\'a\'){\n palindrome[i]=\'a\';\n return palindrome;\n }\n }\n palindrome[n-1]=\'b\';\n return palindrome;\n }\n};\n```
3
0
[]
0
break-a-palindrome
Simple Java Solution:
simple-java-solution-by-cuda_coder-hyvj
\nclass Solution {\n public String breakPalindrome(String palindrome) {\n if(palindrome.length()==1)\n return "";\n char[] a=palindr
cuda_coder
NORMAL
2022-10-10T07:20:14.747015+00:00
2022-10-10T07:20:14.747125+00:00
632
false
```\nclass Solution {\n public String breakPalindrome(String palindrome) {\n if(palindrome.length()==1)\n return "";\n char[] a=palindrome.toCharArray();boolean flag=true;\n for(int i=0;i<a.length/2;i++)\n if(a[i]!=\'a\'){\n a[i]=\'a\';\n flag=false;\n break;\n }\n if(flag==true)\n a[a.length-1]=\'b\';\n return new String(a);\n }\n}\n```
3
0
['String', 'Java']
2
break-a-palindrome
Simple C++ Solution || Runtime 6 ms Beats 16.14% Memory 6 MB
simple-c-solution-runtime-6-ms-beats-161-b1q5
Intuition\nMy first Intuition was to find the inex of frst character using "Binary Search" and then replacing the next character in the original string with the
ahipsharma
NORMAL
2022-10-10T04:48:48.321477+00:00
2022-10-10T04:48:48.321501+00:00
964
false
# Intuition\nMy first Intuition was to find the inex of frst character using "Binary Search" and then replacing the next character in the original string with the previous character. However it didn\'t proved to be an effective solution. So I came up with this second solution.\n\n# Approach\nIt is basically a greedy approach that checks:\n1 - If the length of string is greater than 2, it replaces the first character which is not equal to \'a\' with \'a\'. Example - "**abc**cba" here in the bold part, character at 1st index \'b\' != \'a\' so it replaces with \'a\'.\n2 - if length of string is 2, it replaces the last character with \'b\'.(The edge case \'bb\' will be handled in step 1!!!).\n## ***Hope you loved the explaination. If so please upvote my solution.*\n**\n# Complexity\n- Time complexity:\nTime Complexity is O(n/2) which is O(n);\n\n- Space complexity:\nSpace complexity is O(1). Since no extra space is used by us.\n\n# Code\n```\nclass Solution {\npublic:\n string breakPalindrome(string str){\n int len = str.size(), end = len / 2;\n for (int i = 0; i < len/2; i++){\n if(str[i] != \'a\'){\n str[i] = \'a\';\n return str;\n }\n }\n if(len > 1){\n str[len - 1] = \'b\';\n return str;\n }\n return "";\n }\n};\n```
3
0
['C++']
1
break-a-palindrome
Easy to Understand C++ Code || Short Code
easy-to-understand-c-code-short-code-by-urpl5
\nclass Solution {\npublic:\n string breakPalindrome(string S) {\n int N = S.size();\n if(N == 1) return "";\n int i=0, j=N-1;\n
amancselover
NORMAL
2022-10-10T04:21:43.111426+00:00
2022-10-10T04:21:43.111451+00:00
23
false
```\nclass Solution {\npublic:\n string breakPalindrome(string S) {\n int N = S.size();\n if(N == 1) return "";\n int i=0, j=N-1;\n while(i <= j){\n if(S[i] != \'a\' && i!=N/2){\n S[i] = \'a\';\n return S;\n }\n i++, j--;\n }\n S.back() = \'b\';\n return S;\n }\n};\n```
3
0
[]
1
break-a-palindrome
(C++) 0ms Easy and Simple O(n)
c-0ms-easy-and-simple-on-by-kunalbashist-j410
\nclass Solution {\npublic:\n string breakPalindrome(string p) {\n if(p.size()==1)\n {\n return "";\n }\n int a=0;\n
kunalbashist
NORMAL
2022-10-10T02:32:53.462148+00:00
2022-10-10T07:25:42.554925+00:00
441
false
```\nclass Solution {\npublic:\n string breakPalindrome(string p) {\n if(p.size()==1)\n {\n return "";\n }\n int a=0;\n for(char x: p)\n {\n if(x==\'a\') a++;\n }\n if(a==p.size())\n p[p.size()-1]=\'b\';\n else if(a==p.size()-1 && p.size()&1)\n {\n if(p[p.size()/2]!=\'a\')\n p[p.size()-1]=\'b\';\n }\n else\n {\n for(int i=0;i<p.size()/2+1;i++)\n {\n if(p[i]!=\'a\')\n {\n p[i]=\'a\';\n break;\n }\n }\n }\n return p;\n }\n};\n```\nOptimised way for the above approach is to only iterate half of the string and check for character other than \'a\'.\n```\nclass Solution {\npublic:\n string breakPalindrome(string palindrome) {\n if(palindrome.size()==1)\n {\n return "";\n }\n for(int i=0;i<palindrome.size()/2;i++)\n {\n if(palindrome[i]!=\'a\')\n {\n palindrome[i]=\'a\';\n return palindrome;\n }\n }\n palindrome[palindrome.size()-1]=\'b\';\n return palindrome;\n }\n};\n```
3
0
['C']
0
break-a-palindrome
✅✅Easiest || 4 line of Code || Optimal
easiest-4-line-of-code-optimal-by-arpit5-tvyc
\nclass Solution {\npublic:\n string breakPalindrome(string s) {\n string ans = "";\n int n = s.length();\n /* If given string length ==
Arpit507
NORMAL
2022-10-10T00:16:57.262918+00:00
2022-10-22T06:31:58.495430+00:00
37
false
```\nclass Solution {\npublic:\n string breakPalindrome(string s) {\n string ans = "";\n int n = s.length();\n /* If given string length == 1 then return empty string */\n if(n == 1) return ans;\n \n for(int i = 0;i<n/2;i++){\n /* replace with a */\n if(s[i] != \'a\'){\n s[i] = \'a\';\n return s;\n }\n }\n /* replace last with b \uD83D\uDE02\uD83D\uDE02\uD83D\uDE02 it is done guyz*/\n s[n-1] = \'b\';\n return s;\n }\n};\n```\n\nIf you like it please do Upvote
3
0
['C', 'C++']
0
break-a-palindrome
Python
python-by-blue_sky5-pd2k
\nclass Solution:\n def breakPalindrome(self, palindrome: str) -> str:\n if len(palindrome) == 1:\n return ""\n \n for i in r
blue_sky5
NORMAL
2022-08-01T01:12:29.079888+00:00
2022-08-01T01:12:29.079941+00:00
715
false
```\nclass Solution:\n def breakPalindrome(self, palindrome: str) -> str:\n if len(palindrome) == 1:\n return ""\n \n for i in range(len(palindrome)//2):\n if palindrome[i] != \'a\':\n return palindrome[:i] + \'a\' + palindrome[i+1:]\n \n return palindrome[:-1] + \'b\'\n```
3
0
['Python3']
0
break-a-palindrome
Easy & Clear Solution Python
easy-clear-solution-python-by-moazmar-edle
\nclass Solution:\n def breakPalindrome(self, p: str) -> str:\n if len(p)==1 :\n return ""\n for i in range(len(p)//2):\n
moazmar
NORMAL
2021-09-23T20:51:42.295370+00:00
2021-09-23T20:51:42.295415+00:00
199
false
```\nclass Solution:\n def breakPalindrome(self, p: str) -> str:\n if len(p)==1 :\n return ""\n for i in range(len(p)//2):\n if p[i] != \'a\':\n p=p[0:i]+\'a\'+p[i+1:]\n return p\n return p[0:len(p)-1]+\'b\'\n```
3
0
['Python', 'Python3']
0
break-a-palindrome
[C++] Simple 0ms 6 mb
c-simple-0ms-6-mb-by-ang3r-a9xt
\nclass Solution {\npublic:\n string breakPalindrome(string palindrome) {\n size_t sz = palindrome.size(); \n if (sz == 1)\n return
AnG3R
NORMAL
2021-09-23T18:07:15.888087+00:00
2021-09-23T18:07:15.888141+00:00
316
false
```\nclass Solution {\npublic:\n string breakPalindrome(string palindrome) {\n size_t sz = palindrome.size(); \n if (sz == 1)\n return "";\n for (size_t i = 0; i < sz/2; i++) {\n if (palindrome[i] - \'a\' > 0) {\n palindrome[i] = \'a\';\n return palindrome;\n }\n }\n palindrome[sz-1] = \'b\';\n return palindrome;\n }\n};\n```
3
0
['C']
0
break-a-palindrome
[Kotlin] Clean & Short Solution
kotlin-clean-short-solution-by-catcatcut-sdfp
\nclass Solution {\n fun breakPalindrome(palindrome: String): String {\n return if (palindrome.length == 1) {\n "" // It\'s impassible to b
catcatcute
NORMAL
2021-09-23T10:04:32.262746+00:00
2021-09-23T10:04:32.262776+00:00
117
false
```\nclass Solution {\n fun breakPalindrome(palindrome: String): String {\n return if (palindrome.length == 1) {\n "" // It\'s impassible to break palindrome when length == 1\n } else {\n palindrome.indexOfFirst { it != \'a\' }\n .takeIf {\n it != -1 && it < palindrome.length / 2\n }?.let { index ->\n // If there exist a none \'a\' character in the first half, change that character to \'a\'\n StringBuilder(palindrome).also { it[index] = \'a\' }.toString()\n } ?: run { \n // Else change the last character to \'b\'\n StringBuilder(palindrome).also { it[it.lastIndex] = \'b\' }.toString()\n }\n }\n }\n}\n```
3
0
['Kotlin']
0
break-a-palindrome
60ms Javascript solution
60ms-javascript-solution-by-justraj007-hli0
\nvar breakPalindrome = function(palindrome) {\n if (palindrome.length === 1) return \'\';\n let acount=0;\n \n for (let i=0; i<palindrome.length; i
justraj007
NORMAL
2021-06-20T07:21:30.800721+00:00
2021-06-20T07:21:30.800768+00:00
405
false
```\nvar breakPalindrome = function(palindrome) {\n if (palindrome.length === 1) return \'\';\n let acount=0;\n \n for (let i=0; i<palindrome.length; i++) {\n if (palindrome[i] === \'a\') acount++;\n }\n \n if (palindrome.length-1 === acount) return palindrome.slice(0, palindrome.length-1)+\'b\';\n for (let i=0;i<palindrome.length; i++) {\n if (palindrome[i] !== \'a\') {\n return palindrome.slice(0, i)+\'a\'+palindrome.slice(i+1);\n }\n }\n return palindrome.slice(0, palindrome.length-1)+\'b\';\n};\n```\n\nTime Complexity: O(n)
3
0
['JavaScript']
1
break-a-palindrome
Easy C++ Solution - Faster than 100% with simplest logic
easy-c-solution-faster-than-100-with-sim-ws95
\nclass Solution {\npublic:\n string breakPalindrome(string palindrome) {\n if(palindrome.length() == 1) return "";\n \n for(int i =0; i
warwick78
NORMAL
2021-05-24T16:45:56.375160+00:00
2021-05-24T16:45:56.375200+00:00
141
false
```\nclass Solution {\npublic:\n string breakPalindrome(string palindrome) {\n if(palindrome.length() == 1) return "";\n \n for(int i =0; i < palindrome.length() / 2 ; i++){\n if (palindrome[i] != \'a\') {\n palindrome[i] = \'a\';\n return palindrome;\n }\n }\n palindrome[palindrome.length()-1] = \'b\';\n return palindrome;\n }\n};\n```
3
0
[]
0
break-a-palindrome
[C++] Greedy
c-greedy-by-gagandeepahuja09-1495
1) First I try to insert a character as small as possible to make it non - palindrome. For that I greedily start from first index and the smallest possible char
gagandeepahuja09
NORMAL
2020-01-25T16:04:45.951364+00:00
2020-01-26T06:35:16.609971+00:00
559
false
1) First I try to insert a character as small as possible to make it non - palindrome. For that I greedily start from first index and the smallest possible character till the current character.\n\n2) If this is a non-palindrome now, I just return it.\n\n3) Even after trying this, if it is not a non - palindrome, I try to insert a character greater than the current character. Now, since it would become a larger string, I start from the last index.\n\n4) Even after all this, it is not possible to make it a non-palindrome, return ""\n\n```\nclass Solution {\npublic:\n string breakPalindrome(string s) {\n int n = s.size(); \n for(int i = 0; i < s.size(); i++) {\n char temp = s[i];\n for(char c = \'a\'; c < temp; c++) {\n s[i] = c;\n if(s[i] != s[n - 1 - i]) {\n return s;\n }\n }\n s[i] = temp;\n }\n for(int i = s.size() - 1; i >= 0; i--) {\n char temp = s[i];\n for(char c = temp; c <= \'z\'; c++) {\n s[i] = c;\n if(s[i] != s[n - 1 - i]) {\n return s;\n }\n }\n s[i] = temp;\n }\n return "";\n }\n};\n```
3
0
[]
1
break-a-palindrome
✅✅ Beats 100% || Greedy || Easy Solution
beats-100-greedy-easy-solution-by-karan_-xo6o
Approach1. Handle Edge Case If the palindrome has only one character, it's impossible to break it, so return "". 2. Try to Replace the First Non-'a' Character I
Karan_Aggarwal
NORMAL
2025-03-24T17:13:38.154326+00:00
2025-03-24T17:13:38.154326+00:00
66
false
# Approach ### **1. Handle Edge Case** - If the palindrome has only **one character**, it's impossible to break it, so return `""`. ### **2. Try to Replace the First Non-'a' Character** - Iterate through the **first half** of the string. - If we find a character **not equal to 'a'**, replace it with **'a'** (smallest lexicographical change) and return the modified string. ### **3. If the String is All 'a's** - The palindrome is something like `"aaa"`, `"aaaa"`, etc. - The only way to **break the palindrome** while keeping it lexicographically smallest is by changing the **last character** to `'b'`. # Complexity: - **Time Complexity:** `O(N)` (single pass). - **Space Complexity:** `O(1)` (modifying in-place). # Code ```cpp [] class Solution { public: string breakPalindrome(string palindrome) { int n= palindrome.length(); if(n==1) return ""; for(int i=0;i<n/2;i++){ char ch=palindrome[i]; if(ch!='a'){ palindrome[i]='a'; return palindrome; } } palindrome[n-1]='b'; return palindrome; } }; ``` # Have a Good Day 😊 UpVote?
2
0
['String', 'Greedy', 'C++']
0
break-a-palindrome
Lexicographically Smaller is everything
lexicographically-smaller-is-everything-vr8n6
\n\n# Code\n\nclass Solution {\npublic:\n string breakPalindrome(string palindrome) {\n int n = palindrome.size();\n if (n == 1) {\n
vaibhav_bilwal
NORMAL
2024-07-03T11:19:38.382803+00:00
2024-07-03T11:19:38.382828+00:00
99
false
\n\n# Code\n```\nclass Solution {\npublic:\n string breakPalindrome(string palindrome) {\n int n = palindrome.size();\n if (n == 1) {\n return "";\n }\n for (int i = 0; i < n / 2; ++i) {\n if (palindrome[i] != \'a\') {\n palindrome[i] = \'a\';\n return palindrome;\n }\n }\n palindrome[n - 1] = \'b\';\n return palindrome;\n }\n};\n\n```
2
0
['String', 'Greedy', 'C++']
0
break-a-palindrome
simple and easy C++ solution 😍❤️‍🔥
simple-and-easy-c-solution-by-shishirrsi-ti84
if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n\n# Code\n\nclass Solution {\npublic:\n string breakPalindrome(string s) \n {\n if(s.size() =
shishirRsiam
NORMAL
2024-05-18T18:50:54.087523+00:00
2024-05-18T18:50:54.087543+00:00
40
false
# if it\'s help, please up \u2B06 vote! \u2764\uFE0F\n\n\n# Code\n```\nclass Solution {\npublic:\n string breakPalindrome(string s) \n {\n if(s.size() == 1) return "";\n int i = 0, j = s.size()-1;\n while(i<j)\n {\n if(s[i] != \'a\')\n {\n s[i] = \'a\';\n return s;\n }\n i++, j--;\n }\n s[s.size()-1] = \'b\';\n return s;\n }\n};\n```
2
0
['String', 'Greedy', 'C++']
3
break-a-palindrome
easy c++ code 100%
easy-c-code-100-by-harshith173-8phr
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
harshith173
NORMAL
2024-04-06T09:20:10.377104+00:00
2024-04-06T09:20:10.377137+00:00
6
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 breakPalindrome(String palindrome) {\n char[] cstr = palindrome.toCharArray();\n if(cstr.length<2){\n return "";\n }\n for(int i=0;i<cstr.length/2;i++){\n if(cstr[i]!=\'a\'){\n cstr[i]=\'a\';\n return String.valueOf(cstr);\n }\n }\n cstr[cstr.length-1]=\'b\';\n return String.valueOf(cstr);\n }\n}\n```
2
0
['Java']
0
break-a-palindrome
Easy to Understand Java Code || Beats 100%
easy-to-understand-java-code-beats-100-b-lfwr
Complexity\n- Time complexity:\nO(n)\n- Space complexity:\nO(n)\n# Code\n\nclass Solution {\n public String breakPalindrome(String palindrome) {\n cha
Saurabh_Mishra06
NORMAL
2024-03-16T04:02:39.004724+00:00
2024-03-16T04:02:39.004754+00:00
286
false
# Complexity\n- Time complexity:\nO(n)\n- Space complexity:\nO(n)\n# Code\n```\nclass Solution {\n public String breakPalindrome(String palindrome) {\n char[] s = palindrome.toCharArray();\n for(int i=0; i<s.length/2; i++){\n if(s[i] != \'a\'){\n s[i] = \'a\';\n return new String(s);\n }\n }\n\n s[s.length-1] = \'b\';\n return s.length < 2 ? "" : new String(s); \n }\n}\n```
2
0
['Java']
0
break-a-palindrome
Best Java Solution || Beats 100%
best-java-solution-beats-100-by-ravikuma-35ss
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
ravikumar50
NORMAL
2023-09-29T12:09:57.114738+00:00
2023-09-29T12:09:57.114763+00:00
65
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 breakPalindrome(String s) {\n int n = s.length();\n\n if(n==1) return "";\n\n StringBuilder ans = new StringBuilder(s);\n boolean flag = false;\n\n for(int i=0; i<n/2; i++){\n char ch = ans.charAt(i);\n if(ch!=\'a\'){\n int x = ans.indexOf(ch+"");\n ans.replace(x,x+1,"a");\n flag = true;\n break;\n }\n }\n if(flag==false){ // in case that all character are \'a\'\n ans.replace(n-1,n,"b");\n }\n\n return ans.toString();\n }\n}\n```
2
0
['Java']
0
break-a-palindrome
Easy to understand || 100% faster
easy-to-understand-100-faster-by-thestar-xnaq
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) \nUsing Constant space \n# C
theStark
NORMAL
2022-11-20T04:03:57.188334+00:00
2022-11-20T04:03:57.188374+00:00
17
false
- 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)$$ -->\nUsing Constant space \n# Code\n```\nclass Solution {\npublic:\n string breakPalindrome(string palindrome) {\n int len = palindrome.size();\n if(len == 1){\n return "";\n }\n for(int i=0; i<len/2; i++){\n if(palindrome[i] != \'a\'){\n palindrome[i] = \'a\';\n return palindrome;\n }\n }\n palindrome[len-1] = \'b\';\n return palindrome;\n }\n};\n```
2
0
['Brainteaser', 'C++']
0
break-a-palindrome
JAVA || Greedy Solution||100% Faster Code
java-greedy-solution100-faster-code-by-m-xy68
\n\nPLEASE UPVOTE IF YOU LIKE.\n\n\n# Complexity\n- Time complexity:\n O(N)\n\n- Space complexity:\n O(1)\n\n# Code\n\nclass Solution {\n public String break
manjoor_21
NORMAL
2022-10-27T09:54:06.707192+00:00
2022-10-27T09:59:33.170315+00:00
64
false
\n```\nPLEASE UPVOTE IF YOU LIKE.\n```\n\n# Complexity\n- Time complexity:\n O(N)\n\n- Space complexity:\n O(1)\n\n# Code\n```\nclass Solution {\n public String breakPalindrome(String palindrome) {\n int n = palindrome.length();\n if (n == 1) return "";\n\n StringBuilder sb = new StringBuilder(palindrome);\n boolean flag = true;\n\n for (int i = 0; i < n/2; i++) {\n if (palindrome.charAt(i) != \'a\') {\n sb.setCharAt(i, \'a\');\n flag = false;\n break;\n }\n }\n \n if(flag){\n sb.setCharAt(n - 1, \'b\');\n }\n\n return sb.toString();\n }\n}\n```
2
0
['Java']
0
break-a-palindrome
python easy solution
python-easy-solution-by-karanjadaun22-ebwk
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
karanjadaun22
NORMAL
2022-10-13T05:35:04.509679+00:00
2022-10-13T05:35:04.509706+00:00
110
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:\n def breakPalindrome(self, palindrome: str) -> str:\n if len(palindrome) < 2: return ""\n for i in range(len(palindrome)//2):\n if palindrome[i] != \'a\':\n return palindrome[:i] +\'a\' +palindrome[i+1:]\n return palindrome[:-1]+\'b\'\n```
2
0
['String', 'Python', 'Python3']
0
break-a-palindrome
[Java] Easy to Understand, 100% Fast
java-easy-to-understand-100-fast-by-armo-1d5k
\n\nclass Solution {\n public String breakPalindrome(String palindrome) {\n\t\t// impossible to break length-1 palindrome\n if (palindrome.length() <=
armour42
NORMAL
2022-10-10T23:00:30.768084+00:00
2022-10-10T23:00:41.970480+00:00
579
false
\n```\nclass Solution {\n public String breakPalindrome(String palindrome) {\n\t\t// impossible to break length-1 palindrome\n if (palindrome.length() <= 1) {\n return "";\n }\n char[] sArray = palindrome.toCharArray();\n int lo = 0, hi = sArray.length - 1;\n\t\t// find and replace first non \'a\' with \'a\' from the first half of the palindrome\n\t\t// for odd-length palindromes, exclude the middle character\n while (lo < sArray.length / 2) {\n if (sArray[lo] != \'a\') {\n sArray[lo] = \'a\';\n return new String(sArray);\n }\n lo++;\n }\n\t\t\n\t\t// the first half only has \'a\'s, replace the last character with its next neighbor \n sArray[hi] = (char) ((int) sArray[hi] + 1);\n return new String(sArray);\n }\n}\n```
2
0
['Java']
0
break-a-palindrome
Java Solution without using any additional char array (100% faster)
java-solution-without-using-any-addition-6cj6
class Solution {\n public String breakPalindrome(String palindrome) {\n \n\t\tint n = palindrome.length();\n if (n == 1) return "";\n St
garryk77
NORMAL
2022-10-10T20:49:07.152727+00:00
2022-10-10T20:56:31.744712+00:00
212
false
class Solution {\n public String breakPalindrome(String palindrome) {\n \n\t\tint n = palindrome.length();\n if (n == 1) return "";\n StringBuilder sb = new StringBuilder(palindrome);\n \n\t\t// loop only till n/2 as the string is already given as palindrome\n for (int i=0; i<n/2; i++){\n if(palindrome.charAt(i) != \'a\'){\n sb.setCharAt(i,\'a\');\n return sb.toString();\n }\n }\n \n sb.setCharAt(n-1, \'b\');\n return sb.toString();\n }\n}
2
0
['String', 'Java']
0
break-a-palindrome
Daily LeetCoding challenge
daily-leetcoding-challenge-by-saurabh-hu-50if
\nclass Solution {\n public String breakPalindrome(String palindrome) {\n if(palindrome.length()==1)\n return "";\n \n for(in
saurabh-huh
NORMAL
2022-10-10T20:41:58.896432+00:00
2022-10-10T20:41:58.896471+00:00
121
false
```\nclass Solution {\n public String breakPalindrome(String palindrome) {\n if(palindrome.length()==1)\n return "";\n \n for(int i=0;i<palindrome.length()/2;i++)\n {\n if(palindrome.charAt(i)!=\'a\')\n {\n palindrome = palindrome.substring(0, i) + \'a\' + palindrome.substring(i + 1);\n return palindrome;\n }\n }\n palindrome = palindrome.substring(0,palindrome.length()-1) + \'b\' + palindrome.substring(palindrome.length());\n return palindrome;\n }\n}\n```
2
0
['Java']
0
break-a-palindrome
Python || Simple and fast || Beats 95.7%
python-simple-and-fast-beats-957-by-garv-4573
\nclass Solution:\n def breakPalindrome(self, palindrome: str) -> str:\n if len(palindrome)==1: # Only case where we cannot replace a character to
Garviel77
NORMAL
2022-10-10T19:14:51.960633+00:00
2022-10-10T19:14:51.960664+00:00
290
false
```\nclass Solution:\n def breakPalindrome(self, palindrome: str) -> str:\n if len(palindrome)==1: # Only case where we cannot replace a character to make it "not a plaindrome"\n return \'\'\n\n palindrome = list(palindrome)\n for i in range(len(palindrome)//2): # We only have to check for half of the string because the rest will be exactly the same\n if palindrome[i] != \'a\': # First character that is not \'a\' will be replace with \'a\' to give lexicographically smallest\n palindrome[i] = \'a\'\n return \'\'.join(palindrome) # Here we can also use string slicing, but using a list then .join() is faster \n else:\n\t\t\'\'\' Suppose we are not able to find a character that is not \'a\' in the first half Ex: aaabaaa. Then simply change the last character with \'b\' \'\'\'\n palindrome[-1]=\'b\' \n \n return \'\'.join(palindrome)\n \n```\n
2
0
['Python3']
0
break-a-palindrome
C++ Solution || 0 ms, Faster than 100% of Submissions
c-solution-0-ms-faster-than-100-of-submi-u614
\nclass Solution {\n public:\n string breakPalindrome(string palindrome) {\n set < char > s;\n int n = palindrome.size();\n if (n == 1) retur
saitejabehera
NORMAL
2022-10-10T18:32:12.186086+00:00
2022-10-10T18:32:12.186127+00:00
38
false
```\nclass Solution {\n public:\n string breakPalindrome(string palindrome) {\n set < char > s;\n int n = palindrome.size();\n if (n == 1) return "";\n for (int i = 0; i < (palindrome.size() + 1) / 2; i++) {\n s.insert(palindrome[i]);\n }\n if (s.size() == 1) {\n if (palindrome[0] == \'a\') palindrome[n - 1] = \'b\';\n else palindrome[0] = \'a\';\n return palindrome;\n }\n int cnt = 0;\n for (int i = 0; i < palindrome.size(); i++) {\n if (palindrome[i] != \'a\') {\n if (i != n / 2)\n palindrome[i] = \'a\';\n else {\n for (int k = i + 1; k < n; k++) {\n if (palindrome[k] != \'a\') {\n palindrome[n / 2] = \'a\';\n cnt++;\n break;\n }\n }\n if (!cnt) palindrome[n - 1] = \'b\';\n }\n break;\n }\n }\n return palindrome;\n }\n};\n```
2
0
['C++']
0
break-a-palindrome
✅C++ solution [beats 100% in time] | ☑️ Python solution | [greedy solution]
c-solution-beats-100-in-time-python-solu-ylbm
Please upvote to motivate me to write more solutions\n\n# Code [C++ beats 100% & 70%]\n\nclass Solution {\npublic:\n string breakPalindrome(string palindrome
coding_menance
NORMAL
2022-10-10T17:56:31.276080+00:00
2022-10-19T13:55:38.242043+00:00
79
false
*Please upvote to motivate me to write more solutions*\n\n# Code [C++ beats 100% & 70%]\n```\nclass Solution {\npublic:\n string breakPalindrome(string palindrome) {\n \n for (int i=0; i<palindrome.length()/2; i++) {\n if (palindrome[i] != \'a\') {\n palindrome[i] = \'a\';\n return palindrome;\n }\n }\n\n palindrome[palindrome.length()-1]=\'b\';\n return palindrome.length() > 1 ? palindrome : "";\n }\n};\n```\n\n# Code [Python beats 21% & 61%]\n\n```\nclass Solution:\n def breakPalindrome(self, palindrome: str) -> str:\n palindrome=list(palindrome)\n for i in range(int(len(palindrome)/2)):\n if palindrome[i]!="a":\n palindrome[i]=\'a\'\n return "".join(palindrome)\n palindrome[len(palindrome)-1] = \'b\'\n if len(palindrome)>1:\n return "".join(palindrome)\n else:\n return ""\n```
2
0
['Greedy', 'Python', 'C++', 'Python3']
0
break-a-palindrome
JAva || String fastest Solution || 0ms
java-string-fastest-solution-0ms-by-spir-t1j0
\nclass Solution {\n public String breakPalindrome(String palindrome) {\n // Code here\n if(palindrome.length() == 1)\n return "";\n
Spirited-Coder
NORMAL
2022-10-10T17:20:07.214673+00:00
2022-10-10T17:20:07.214711+00:00
985
false
```\nclass Solution {\n public String breakPalindrome(String palindrome) {\n // Code here\n if(palindrome.length() == 1)\n return "";\n \n char[] ch = palindrome.toCharArray(); \n \n for(int i = 0; i < palindrome.length()/2; i++)\n {\n if(ch[i] != \'a\')\n {\n ch[i] = \'a\';\n break;\n }\n else if(i == palindrome.length()/2 - 1 && ch[i] == \'a\')\n ch[ch.length -1] = \'b\';\n }\n \n return new String(ch);\n }\n}\n```
2
0
['String', 'Java']
1
break-a-palindrome
Best O(N) Python Solution Explained
best-on-python-solution-explained-by-blo-e8v8
O(N) Python Solution\n\ndef breakPalindrome(self, palindrome: str) -> str:\n\tn = len(palindrome) # store palindrome length\n\tif n == 1: # no way to make 1 let
bloomh
NORMAL
2022-10-10T16:59:10.966564+00:00
2022-10-10T16:59:10.966599+00:00
1,560
false
**O(N) Python Solution**\n```\ndef breakPalindrome(self, palindrome: str) -> str:\n\tn = len(palindrome) # store palindrome length\n\tif n == 1: # no way to make 1 letter not a palindrome\n\t\treturn ""\n\tfor i in range(n//2): # go through the first half of the palindrome\n\t\tif palindrome[i] != "a": # if it is not an "a" then we can make it lexicographically smaller\n\t\t\treturn palindrome[:i] + "a" + palindrome[i+1:] # replace character with an "a"\n\treturn palindrome[:-1] + "b" # if all "a", then replace the last one with a "b"\n```\n\n**Explanation**\nThe idea behind this solution is that we want to make the string lexicographically smaller, so whenever there is an opportunity to turn a character which is not ```a``` into ```a```, we should. We only need to check the first ```n//2``` indices because we know that the input is a palindrome, so anything in the first ```n//2``` spots will be mirrored. If the string has an odd length, we cannot change the middle character since then the string would still be a palindrome. If we never find a character which is not ```a```, then we have to change one of the characters to ```b```. We want to add this to the end of the string since that minimizes the lexicographic value. We also have to check the length of ```palindrome``` is ```1``` since then there is no way to turn it into a non-palindrome, so we return ```""```.\n\n**Complexity**\nThis solution takes ```O(n)``` time since the number of characters we need to check scales with the length of ```palindrome```. It takes constant space since the memory we use does not change with the size of ```palindrome```.\n\n**Thanks for Reading!**\nIf this post has been helpful, please consider upvoting! If you have any questions, please feel free to ask in the comments and I will try to answer them. Also, if I made any mistakes or there are other optimizations, methods I didn\'t consider, etc. please let me know!
2
0
['Greedy', 'Python']
1
break-a-palindrome
Easiest java solution || Simple logic || 0ms || Faster than 100% | Fully Commented Code
easiest-java-solution-simple-logic-0ms-f-56y4
\tclass Solution {\n\t\tpublic String breakPalindrome(String palindrome) {\n\t\t\t// If the string contains only one char then we will simply return blank strin
AtishDey13
NORMAL
2022-10-10T16:20:15.557835+00:00
2022-10-11T04:23:55.295096+00:00
83
false
\tclass Solution {\n\t\tpublic String breakPalindrome(String palindrome) {\n\t\t\t// If the string contains only one char then we will simply return blank string \n\t\t\tif(palindrome.length()==1) return "";\n\t\t\tStringBuilder answer = new StringBuilder(palindrome);\n\t\t\t// If the string contains all the \'a\'s or only one char other than \'a\' which is in the middle,\n\t\t\t//then we can simply change the last char to \'b\'. This will make the string non-palindromic \n\t\t\t//and will be lexiographically smallest.\n\t\t\tif(isThisStringAnEdgeCase(palindrome)) {\n\t\t\t\tanswer.setCharAt(palindrome.length()-1 , \'b\');\n\t\t\t} \n\t\t\t// Here we will simply find the first char which is not \'a\', convert it to \'a\' and the string will become non-palindromic.\n\t\t\telse {\n\t\t\t\tfor(int i=0;i<answer.length();i++) {\n\t\t\t\t\tif(answer.charAt(i)!=\'a\') {\n\t\t\t\t\t\tanswer.replace(i,i+1,"a");\n\t\t\t\t\t\tbreak;\n\t\t\t\t\t}\n\t\t\t\t} \n\t\t\t}\n\t\t\treturn answer.toString();\n\t\t}\n\n\t\t/**\n\t\t* This method will return true if every chacter is \'a\' or if the string contains only one \n\t\t* character that is other than \'a\' and it\'s placed in the middle.\n\t\t* You can choose a better name for the method ;)\n\t\t*/\n\t\tprivate boolean isThisStringAnEdgeCase(String palindrome) {\n\t\t\tint start = 0;\n\t\t\tint end = palindrome.length()-1;\n\t\t\twhile(start<end) {\n\t\t\t\tif(palindrome.charAt(start)!=\'a\' || palindrome.charAt(end)!=\'a\') {\n\t\t\t\t\treturn false;\n\t\t\t\t}\n\t\t\t\tstart++;\n\t\t\t\tend--;\n\t\t\t}\n\t\t\treturn true;\n\t\t}\n\t}
2
0
['Java']
0
break-a-palindrome
Pythonic linear solution
pythonic-linear-solution-by-dineshrajan-g4yl
\nclass Solution:\n def breakPalindrome(self, palindrome: str) -> str:\n \n if len(palindrome)==1:\n return ""\n\n m = len(pa
dineshrajan
NORMAL
2022-10-10T16:14:06.496210+00:00
2022-10-10T16:14:06.496249+00:00
168
false
```\nclass Solution:\n def breakPalindrome(self, palindrome: str) -> str:\n \n if len(palindrome)==1:\n return ""\n\n m = len(palindrome)//2\n \n for ch in range(0,m):\n if palindrome[ch] != \'a\':\n return palindrome[0:ch]+\'a\'+palindrome[ch+1:]\n return palindrome[:-1]+\'b\'\n\t\t```
2
0
['String']
2
break-a-palindrome
C++ easy approch solution
c-easy-approch-solution-by-the_sharma_ha-q0r6
class Solution {\npublic:\n string breakPalindrome(string p)\n {\n if(p.size()<=1)\n return "";\n for(int i=0;i<p.size()/2;i++)\n
the_sharma_harsh
NORMAL
2022-10-10T15:58:48.912425+00:00
2022-10-10T15:58:48.912452+00:00
1,664
false
class Solution {\npublic:\n string breakPalindrome(string p)\n {\n if(p.size()<=1)\n return "";\n for(int i=0;i<p.size()/2;i++)\n {\n if(p[i]!=\'a\')\n {\n p[i]=\'a\';\n return p;\n break;\n }\n }\n p[p.size()-1]=\'b\';\n return p;\n }\n};
2
0
[]
0
break-a-palindrome
C++ simple easy concise solution
c-simple-easy-concise-solution-by-sharma-a0u8
class Solution {\npublic:\n string breakPalindrome(string palindrome)\n {\n if(palindrome.length()<=1)\n return "";\n for(int i=0
sharma_harsh_glb
NORMAL
2022-10-10T15:52:47.088588+00:00
2022-10-10T15:52:47.088628+00:00
894
false
class Solution {\npublic:\n string breakPalindrome(string palindrome)\n {\n if(palindrome.length()<=1)\n return "";\n for(int i=0;i<palindrome.size()/2;i++)\n {\n if(palindrome[i]!=\'a\')\n {\n palindrome[i]=\'a\';\n return palindrome;\n break;\n }\n }\n palindrome[palindrome.size()-1]=\'b\';\n return palindrome;\n }\n};
2
0
[]
0
break-a-palindrome
C# StringBuilder
c-stringbuilder-by-gregsklyanny-mfv1
Please upvote if my solution was helpful ;)\n\npublic class Solution {\n public string BreakPalindrome(string palindrome) \n\t{\n \n int pLengt
gregsklyanny
NORMAL
2022-10-10T14:14:01.113489+00:00
2022-12-12T15:49:47.659343+00:00
87
false
**Please upvote if my solution was helpful ;)**\n```\npublic class Solution {\n public string BreakPalindrome(string palindrome) \n\t{\n \n int pLength = palindrome.Length; \n if(pLength == 1) return "";\n var sb = new StringBuilder(palindrome);\n for(int i=0; i < pLength/2; i++)\n\t\t{\n if(palindrome[i]!=\'a\')\n\t\t\t{ \n sb[i] = \'a\';\n return sb.ToString();\n }\n } \n\t\tsb[pLength-1] = \'b\';\n\t\treturn sb.ToString(); \n }\n}\n```
2
0
['C#']
0
break-a-palindrome
Fastest Solution Beats 100%
fastest-solution-beats-100-by-suryansh_k-rc0o
class Solution {\n\n public String breakPalindrome(String palindrome) {\n\tint n=palindrome.length();\n char[] CA=palindrome.toCharArray();\n i
Suryansh_Katiyar
NORMAL
2022-10-10T13:40:02.260118+00:00
2022-10-10T13:40:41.018703+00:00
516
false
class Solution {\n\n public String breakPalindrome(String palindrome) {\n\tint n=palindrome.length();\n char[] CA=palindrome.toCharArray();\n if(n==1) return "";\n for(int i=0;i<n/2;i++){\n if(CA[i]!=\'a\') {\n CA[i]=\'a\'; \n return new String(CA); }}\n CA[n-1]=\'b\';\n return new String(CA);}}
2
0
['Array', 'String', 'Java']
1
break-a-palindrome
C++, Golang | both faster than 100%
c-golang-both-faster-than-100-by-mbi-sve4
Golang:\n\nfunc breakPalindrome(s string) string {\n if len(s)==1{\n return ""\n }\n for i:=0; i<len(s)/2; i++ {\n if s[i]!=\'a\' {\n
mbi
NORMAL
2022-10-10T13:39:04.506058+00:00
2022-10-10T13:39:04.506097+00:00
88
false
Golang:\n```\nfunc breakPalindrome(s string) string {\n if len(s)==1{\n return ""\n }\n for i:=0; i<len(s)/2; i++ {\n if s[i]!=\'a\' {\n s=s[:i]+"a"+s[i+1:]\n return s\n }\n }\n s=s[:len(s)-1]+"b"\n return s\n}\n```\n\nC++:\n```\nclass Solution {\npublic:\n string breakPalindrome(string p) {\n if (p.size()==1) return "";\n for (int i=0; i<p.size()/2; i++){\n if (p[i]!=\'a\'){\n p[i]=\'a\';\n return p;\n }\n }\n p.end()[-1]=\'b\';\n return p;\n }\n};\n```
2
0
['C', 'C++', 'Go']
0
break-a-palindrome
Java 100% 0ms | Simple Approach w/ Video Explanation
java-100-0ms-simple-approach-w-video-exp-7wrq
Please Upvote if you find this Explanation helpful\n\nVideo Explanation\nBreak a Palindrome | YouTube\n\nJava Solution\n\n//0ms\nclass Solution {\n public St
sagnik_20
NORMAL
2022-10-10T12:20:12.858042+00:00
2022-10-10T12:20:12.858083+00:00
251
false
*Please **Upvote** if you find this Explanation helpful*\n\n**Video Explanation**\n[Break a Palindrome | YouTube](https://www.youtube.com/watch?v=dIcNa1Oi8xU&feature=youtu.be)\n\n**Java Solution**\n```\n//0ms\nclass Solution {\n public String breakPalindrome(String palindrome) {\n if(palindrome.length() <= 1)\n return "";\n char[] ar = palindrome.toCharArray();\n \n for(int i=0;i<ar.length/2;i++)\n if(ar[i] != \'a\'){\n ar[i] = \'a\';\n return String.valueOf(ar);\n }\n \n ar[ar.length -1] = \'b\';\n return String.valueOf(ar);\n }\n}\n```
2
0
['Java']
1
break-a-palindrome
✅C++|| Simple Iteration || Easy Solution
c-simple-iteration-easy-solution-by-indr-oadg
\nclass Solution {\npublic:\n string breakPalindrome(string palindrome) {\n int n = palindrome.size();\n if(n <= 1) return "";\n \n
indresh149
NORMAL
2022-10-10T10:34:29.992715+00:00
2022-10-10T10:34:29.992746+00:00
37
false
```\nclass Solution {\npublic:\n string breakPalindrome(string palindrome) {\n int n = palindrome.size();\n if(n <= 1) return "";\n \n for(int i=0;i<n/2;i++){\n if(palindrome[i] != \'a\'){\n palindrome[i] = \'a\';\n return palindrome;\n }\n }\n palindrome[n-1] = \'b\';\n return palindrome;\n }\n};\n```\n**Please upvote if it was helpful for you, thank you!**
2
0
['C']
0
break-a-palindrome
Java 100% | Greedy | O(n) | easy
java-100-greedy-on-easy-by-tanx4-h15t
\nclass Solution {\n public String breakPalindrome(String s) {\n \n int l=s.length();\n if(l==1)\n return("");\n \n
tanx4
NORMAL
2022-10-10T09:44:18.083975+00:00
2022-10-10T09:46:13.119012+00:00
54
false
```\nclass Solution {\n public String breakPalindrome(String s) {\n \n int l=s.length();\n if(l==1)\n return("");\n \n char ch[]=s.toCharArray();\n for(int i=0;i<ch.length/2;i++)\n {\n \n if(ch[i]!=\'a\')\n {\n ch[i]=\'a\';\n return(String.valueOf(ch));\n }\n }\n \n ch[l-1]++;\n return(String.valueOf(ch));\n \n \n }\n}\n```
2
0
['Greedy', 'Java']
0
break-a-palindrome
java || hindi || faster than 100%
java-hindi-faster-than-100-by-ersarthaks-8wt9
\nclass Solution {\n public String breakPalindrome(String s) {\n int len = s.length();\n StringBuilder sb = new StringBuilder(s);\n if(l
ersarthaksethi
NORMAL
2022-10-10T09:27:19.209731+00:00
2022-10-10T09:29:28.830437+00:00
25
false
```\nclass Solution {\n public String breakPalindrome(String s) {\n int len = s.length();\n StringBuilder sb = new StringBuilder(s);\n if(len<=1) {\n return "";\n }\n // since its a pallindrome, we will check for only half string\n // agar odd h to len/2 , even hai to len/2+1, tak loop chaalo\n int endpoint = len%2==0 ? len/2 : (len/2)+1;\n // ek variable rakha, jisse pta chle change hua ya nhi\n boolean changed = false;\n for(int i=0;i<endpoint;i++) {\n /*\n LOGIC SAMJO\n jo bhi string h usme , sabse pehle jo character aa rha, jo \'a\' nhi h , usko \'a\' krdo, to smallest leographic hoga\n */\n \n if(s.charAt(i)!=\'a\') {\n // SPECIAL CASE (read it later neeche padh lo fr aana)\n /*maanlo aabaa input h, ab agar \'b\' ko \'a\' krdiya, to pallindrome bn gya \n aabaa, lelo isme agar i = endpoint-1,\n endpoint = 5/2+1 = 3;\n i agar aab me 2 pe ho, mtlb \'b\' par, endpoint-1==2\n to agar hum \'b\' par hai and usse agle char bhi \'a\' hai\n and pichle to saare \'a\' hai hi, nhi to neeche wala break krdeta naa\n */\n if(i==endpoint-1 && s.charAt(i+1)==\'a\') {\n break;\n }\n // \'a\' nhi h , a krdo\n sb.setCharAt(i,\'a\');\n // a krdiya to change true\n changed = true;\n // ho gya naa change break krdo , aage kyu jaana\n break;\n }\n }\n /* ab agar change nhi hua\n to yaa to aaaa, aaa, aabaa, aisa kuch raha hoga,\n is case me ya to saare \'a\' hai, yaaa fr vo wala case jisme middle element alag h ,\n par usko change krde to pallindorme bn jaata, like \'aabaa\' me b ko a krdiya to \'aaaaa\'\n to humnne soch aakhri index pe jo \'a\' hai usko \'b\' krdo\n */\n if(!changed) {\n if(s.equals(sb.toString())) {\n sb.setCharAt(len-1,\'b\');\n }\n }\n return sb.toString();\n }\n}\n```
2
0
[]
1
break-a-palindrome
Rust | Greedy | With Comments
rust-greedy-with-comments-by-wallicent-p236
For strings of length < 2 it is impossible to break the palindrome (as shown in the problem example). For other cases, scan the first half of the string (exclud
wallicent
NORMAL
2022-10-10T07:37:08.807477+00:00
2022-10-10T10:39:41.619095+00:00
114
false
For strings of length < 2 it is impossible to break the palindrome (as shown in the problem example). For other cases, scan the first half of the string (excluding the midpoint element, if any, since a change to that letter would not break the palindrome), and change the first non-`a` to an `a`, if found. That breaks the palindrome and makes the string as lexicographically small as possible. If not found, the string is only `a`s (except possibly for the midpoint element), and we break the palindrome by changing the last letter to a `b`, i.e. preserving as many initial `a`s as possible.\n\nImplementation notes:\n\n* Using e.g. `iter_mut` and `last` to avoid manual indexing.\n* Since input is ASCII, we can use bytes to represent characters, and avoid the overhead of UTF-8 parsing.\n\n```\nimpl Solution {\n pub fn break_palindrome(palindrome: String) -> String {\n let n = palindrome.len();\n if n < 2 {\n String::new()\n } else {\n let mut palindrome = palindrome.as_bytes().to_vec();\n match palindrome.iter_mut().take(n/2).find(|b| **b != b\'a\') {\n Some(b) => *b = b\'a\',\n None => *palindrome.last_mut().unwrap() = b\'b\',\n }\n palindrome.into_iter().map(|b| b as char).collect()\n }\n \n }\n}\n```
2
0
['Rust']
1
break-a-palindrome
📌Most easy || C++||✅✅ || Intuitive|| Smallest Solution
most-easy-c-intuitive-smallest-solution-ljdkg
Inorder to get the smallest lexographical string, the simple Intuition would be that we will convert the first non-\'a\' character to \'a\' which does not hav
RITIKA_NAGAR_09
NORMAL
2022-10-10T06:48:19.425638+00:00
2022-10-10T06:48:19.425670+00:00
26
false
* Inorder to get the smallest lexographical string, the simple Intuition would be that we will convert the first non-\'a\' character to \'a\' which does not have \'a\' on its palindrome corners (i.e at start and end). so that it both does not become \'a\' this is how we will be able to obtain smallest break palindrome.\n* One of the edge case would what if we have string which contains only \'a\', like \'\'aaaaaa\'\' then we will simply convert the last character of string to \'b\' to make it smallest i.e \'\'aaaaab\'\'.\n\n```\nclass Solution {\npublic:\n string breakPalindrome(string palindrome) {\n int l=0; r=n-1;\n if(palindrome.length()<=1){\n return "";\n }\n \n while(l<r){\n if(palindrome[l]!=\'a\' && palindrome[r]!=\'a\'){\n palindrome[l]=\'a\';\n return palindrome;\n }else{\n l++;\n r--;\n }\n }\n \n palindrome[n-1]=\'b\';\n return palindrome;\n }\n};\n```
2
0
['Two Pointers', 'C']
0
break-a-palindrome
Javascript O(n) faster than 99.09%
javascript-on-faster-than-9909-by-yash-d-64bs
Runtime: 57 ms, faster than 99.09% of JavaScript online submissions for Break a Palindrome. Memory Usage: 41.8 MB, less than 68.18% of JavaScript online submiss
yash-devasp
NORMAL
2022-10-10T06:23:48.390190+00:00
2022-10-10T06:23:48.390216+00:00
178
false
Runtime: 57 ms, faster than 99.09% of JavaScript online submissions for Break a Palindrome. Memory Usage: 41.8 MB, less than 68.18% of JavaScript online submissions for Break a Palindrome.\n\nApproach : Changing the first alphabet that is not \'a\' to \'a\' making the string lexicographically the smallest one. Special case handling - In a case where all the character in the string are \'a\' then replacing the last \'a\' with \'b\' makes the best llexicographically smallest string.\n\n```\nvar breakPalindrome = function(palindrome) {\n if(palindrome.length === 1){\n return "";\n }\n let res = "";\n for(let i=0; i < (Math.floor(palindrome.length / 2));i++){\n if(palindrome[i] !== \'a\'){\n res = palindrome.slice(0,i) + \'a\' + palindrome.slice(i+1,palindrome.length);\n break;\n }\n }\n if(res === ""){\n res = palindrome.slice(0,palindrome.length-1) + \'b\';\n }\n return res;\n};\n```
2
0
['Greedy', 'JavaScript']
0
break-a-palindrome
Faster then 100 %
faster-then-100-by-janender0707-jppk
\nclass Solution {\npublic:\n string breakPalindrome(string p) {\n if(p.size()==1)return "";\n for(int i=0;i<p.size()/2;i++){\n if(p[i]!=\'a\'
janender0707
NORMAL
2022-10-10T06:04:03.772916+00:00
2022-10-10T06:04:03.772959+00:00
272
false
```\nclass Solution {\npublic:\n string breakPalindrome(string p) {\n if(p.size()==1)return "";\n for(int i=0;i<p.size()/2;i++){\n if(p[i]!=\'a\'){\n p[i]=\'a\';\n return p;\n }\n }\n p[p.size()-1]=\'b\';\n return p;\n }\n};\n```
2
0
['C', 'C++']
0
break-a-palindrome
Short concise solution o(n/2)
short-concise-solution-on2-by-tan_b-qhiu
\nclass Solution\n{\n public:\n\n string breakPalindrome(string p)\n {\n if (p.size() == 1)\n return "";\n
Tan_B
NORMAL
2022-10-10T04:57:33.394603+00:00
2022-10-10T04:57:33.394638+00:00
13
false
```\nclass Solution\n{\n public:\n\n string breakPalindrome(string p)\n {\n if (p.size() == 1)\n return "";\n string ans = p;\n for (int i = 0; i < p.size() / 2; i++)\n {\n if (p[i] != \'a\')\n {\n ans[i] = \'a\';\n return ans;\n }\n }\n ans.back() = \'b\';\n return ans;\n }\n};\n```
2
0
[]
0
break-a-palindrome
Python | Pretty Simple and clean solution with comments
python-pretty-simple-and-clean-solution-5t0l5
\nclass Solution:\n def breakPalindrome(self, palindrome: str) -> str:\n lst = list(palindrome)\n # if there is noway to make it non-palindromi
__Asrar
NORMAL
2022-10-10T04:49:55.123509+00:00
2022-10-10T04:49:55.123537+00:00
164
false
```\nclass Solution:\n def breakPalindrome(self, palindrome: str) -> str:\n lst = list(palindrome)\n # if there is noway to make it non-palindromic\n if len(lst) < 2:\n return \'\'\n \n # checking till mid if not a make it a\n for i in range(len(lst)//2):\n if lst[i] != \'a\':\n lst[i] = \'a\'\n return \'\'.join(lst)\n \n # else make the last char \'b\'\n lst[len(lst) - 1] = \'b\'\n return \'\'.join(lst)\n \n```\n***Please do upvote if found helpful!!!***
2
0
['String', 'Python', 'Python3']
0
break-a-palindrome
✔ || C++ Easy Solution with edge case Explanation backtrack
c-easy-solution-with-edge-case-explanati-jyab
\nclass Solution {\npublic:\n bool ispal(string s){\n int l=0,r=s.size()-1;\n while(l<r)\n if(s[l++]!=s[r--]) return false;\n ret
user8629ED
NORMAL
2022-10-10T04:00:20.544845+00:00
2022-10-10T04:00:20.544986+00:00
32
false
```\nclass Solution {\npublic:\n bool ispal(string s){\n int l=0,r=s.size()-1;\n while(l<r)\n if(s[l++]!=s[r--]) return false;\n return true;\n }\n string breakPalindrome(string pal) {\n if(pal.size()==1) return "";\n for(int i=0;i<pal.size();i++){\n if(pal[i]!=\'a\'){\n char ch=pal[i];\n pal[i]=\'a\';\n if(ispal(pal)) {pal[i]=ch; break;} // Lets assume "aba" string, our string become "aaa" it is palindrome ,so here we have to cheak after operation string become palindrome or not , if palindrome then make the string back to previous one and change the last element to \'b\n return pal;\n }\n }\n pal[pal.size()-1]=\'b\';\n return pal;\n }\n};\n**If U Like It Please Upvote.**\n```
2
0
['Greedy', 'C']
0
break-a-palindrome
Simple for loop || Beginner Approach || C++best Solution ;
simple-for-loop-beginner-approach-cbest-l6h6u
\t\tif(p.length() == 1) return ""; // only case we not able to make solution ;\n for(int i=0; i<p.length()/2; i++){ // if we use loop till leng
anilsuthar
NORMAL
2022-10-10T03:37:58.039742+00:00
2022-10-10T03:40:39.863617+00:00
27
false
\t\tif(p.length() == 1) return ""; // only case we not able to make solution ;\n for(int i=0; i<p.length()/2; i++){ // if we use loop till lenght it will give wrong output on "aba" ;\n if(p[i] != \'a\') {\n\t\t\t\tp[i] = \'a\';\n return p;\n\t\t\t}\n }\n p[p.length()-1] = \'b\';\n return p;\n\t\t\n\t\t\n\t\t\n**share your experience in comment box**
2
0
['C', 'Java']
0
break-a-palindrome
Beginner friendly [Java/JavaScript/Python] Solution
beginner-friendly-javajavascriptpython-s-nphd
Java\n\nclass Solution {\n public String breakPalindrome(String palindrome) {\n if(palindrome.length() == 1) return "";\n char[] s = palindr
HimanshuBhoir
NORMAL
2022-10-10T03:13:03.347149+00:00
2022-10-10T03:13:03.347193+00:00
107
false
**Java**\n```\nclass Solution {\n public String breakPalindrome(String palindrome) {\n if(palindrome.length() == 1) return "";\n char[] s = palindrome.toCharArray();\n for(int i=0; i<s.length/2; i++){\n if(s[i] != \'a\'){\n s[i] = \'a\';\n return String.valueOf(s);\n }\n }\n s[s.length-1] = \'b\';\n return String.valueOf(s);\n }\n}\n```\n**JavaScript**\n```\nvar breakPalindrome = function(palindrome) {\n if(palindrome.length == 1) return "";\n let s = palindrome.split(\'\')\n for(let i=0; i<~~(s.length/2); i++){\n if(s[i] != \'a\'){\n s[i] = \'a\';\n return s.join(\'\');\n }\n }\n s[s.length-1] = \'b\';\n return s.join(\'\');\n};\n```\n**Python**\n```\nclass Solution(object):\n def breakPalindrome(self, palindrome):\n if len(palindrome) == 1:\n return ""\n for i in range(len(palindrome)/2):\n if palindrome[i] != \'a\':\n return palindrome[:i] + \'a\' + palindrome[i+1:]\n return palindrome[:-1] + \'b\' \n```
2
0
['Python', 'Java', 'JavaScript']
0
break-a-palindrome
EZ python solution
ez-python-solution-by-numpyhh-hggb
\nclass Solution:\n def breakPalindrome(self, palindrome: str) -> str:\n le = len(palindrome)\n \n if le == 1:\n return ""\n
numpyhh
NORMAL
2022-10-10T02:51:48.769934+00:00
2022-10-10T02:51:48.769973+00:00
675
false
```\nclass Solution:\n def breakPalindrome(self, palindrome: str) -> str:\n le = len(palindrome)\n \n if le == 1:\n return ""\n \n for i in range(0, le // 2):\n if palindrome[i] != \'a\':\n return palindrome[:i] + \'a\' + palindrome[i+1:]\n \n return palindrome[:le-1] + \'b\'\n```
2
0
['Python']
1
break-a-palindrome
Python easy solution
python-easy-solution-by-praknew01-wcm5
\nclass Solution:\n def breakPalindrome(self, p: str) -> str:\n if len(p)==1:return ""\n l=list(p)\n for x in range(len(l)//2):\n
praknew01
NORMAL
2022-10-10T00:44:13.393413+00:00
2022-10-10T00:44:13.393452+00:00
118
false
```\nclass Solution:\n def breakPalindrome(self, p: str) -> str:\n if len(p)==1:return ""\n l=list(p)\n for x in range(len(l)//2):\n if l[x]!=\'a\':\n l[x]=\'a\'\n return \'\'.join(l)\n l[-1]=\'b\'\n return \'\'.join(l)\n```
2
0
['Python']
0
break-a-palindrome
DAILY LEETCODE SOLUTION || BREAK A PALINDROME
daily-leetcode-solution-break-a-palindro-gkrl
\nclass Solution {\npublic:\n string breakPalindrome(string palindrome) {\n int n=palindrome.size();\n if(n==1) return "";\n if(n%2==0)\
pankaj_777
NORMAL
2022-10-10T00:31:23.521564+00:00
2022-10-10T00:31:23.521629+00:00
55
false
```\nclass Solution {\npublic:\n string breakPalindrome(string palindrome) {\n int n=palindrome.size();\n if(n==1) return "";\n if(n%2==0)\n {\n int idx=-1;\n for(int i=0;i<n;i++)\n {\n if(palindrome[i]!=\'a\')\n {\n idx=i;\n palindrome[i]=\'a\';\n break;\n }\n }\n if(idx==-1)\n {\n palindrome[n-1]=\'b\';\n }\n return palindrome;\n }\n else\n {\n int idx=-1;\n for(int i=0;i<n;i++)\n {\n if(palindrome[i]!=\'a\'&&i!=n/2)\n {\n idx=i;\n palindrome[idx]=\'a\';\n break;\n }\n }\n if(idx==-1)\n {\n palindrome[n-1]=\'b\';\n }\n return palindrome;\n }\n }\n};\n```
2
0
['String', 'Greedy', 'C']
0
break-a-palindrome
0 ms | Faster than 100%
0-ms-faster-than-100-by-aryan_sri123-iqtj
If string size is 1, return an empty string.\n2. If lowest charcter in string is not \'a\', simply set string[0] = \'a\' and return string.\n3. Else now we ha
aryan_sri123
NORMAL
2022-08-19T10:05:38.793597+00:00
2022-08-19T10:05:38.793665+00:00
154
false
1. If string size is 1, return an empty string.\n2. If lowest charcter in string is not \'a\', simply set string[0] = \'a\' and return string.\n3. Else now we have to convert a char in string to \'a\' such that resultant is of minimum lexicographical order. For that we will check first non-occurence of any other charcter than \'a\' in that string and replace it with \'a\', If we don\'t find any occurence of any other character in that string, that simply means that string contains only of letter \'a\', so in that case we will change last char of string to \'b\';\n4. **Most Important point** In case where string= "aba", we cannot convert \'b\' into \'a\', so for this I have checked for a very intersting case, do check in my code and comment.\n\n\t\t\t\t\t\n\t\t\t\t\tstring breakPalindrome(string s) {\n\t\t\t\t\t\tif(s.size()==1) return "";\n\t\t\t\t\t\tchar lowest=\'z\';\n\t\t\t\t\t\tfor(auto i:s){\n\t\t\t\t\t\t\tif(i<lowest) lowest=i;\n\t\t\t\t\t\t}\n\t\t\t\t\t\tif(lowest!=\'a\') {s[0]=\'a\'; return s;}\n\n\t\t\t\t\t\tint i=0,j=s.size()-1;\n\t\t\t\t\t\twhile(i<=j){\n\t\t\t\t\t\t\tif(s[i]!=lowest) {\n\t\t\t\t\t\t\t\tif((j+1)%2!=0 && i==(j+1)/2) {i++; continue;}\n\t\t\t\t\t\t\t\ts[i]=lowest; \n\t\t\t\t\t\t\t\treturn s;\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\ti++;\n\t\t\t\t\t\t}\n\t\t\t\t\t\ts[j] = lowest+1;\n\t\t\t\t\t\treturn s;\n\t\t\t\t\t}\n
2
0
['String', 'C']
0
prime-arrangements
Simple Java With comment [sieve_of_eratosthenes]
simple-java-with-comment-sieve_of_eratos-1vwn
Used sieve of eratosthenes to generate count prime no \n\n public static int countPrimes(int n) {\n boolean[] prime = new boolean[n + 1];\n Arr
jatinyadav96
NORMAL
2019-09-01T04:14:23.937764+00:00
2019-09-01T04:14:23.937800+00:00
8,480
false
Used sieve of eratosthenes to generate count prime no \n```\n public static int countPrimes(int n) {\n boolean[] prime = new boolean[n + 1];\n Arrays.fill(prime, 2, n + 1, true);\n for (int i = 2; i * i <= n; i++)\n if (prime[i])\n for (int j = i * i; j <= n; j += i)\n prime[j] = false;\n int cnt = 0;\n for (int i = 0; i < prime.length; i++)\n if (prime[i])\n cnt++;\n\n return cnt;\n }\n```\nif you dont know what is sieve of eratosthenes read this\nhttps://www.geeksforgeeks.org/sieve-of-eratosthenes/\n\nAfter getting count of prime \'pn\'\ncalculate no fo arragement of prime numbers i.e pn!\ncalculate no fo arragement of non-prime numbers i.e (n-pn)!\n\nafterwards simple multiply them I used BigInteger of java\n\nHope you will like it :P\n```\n\n static int MOD = 1000000007;\n\n public static int numPrimeArrangements(int n) {\n int noOfPrime = generatePrimes(n);\n BigInteger x = factorial(noOfPrime);\n BigInteger y = factorial(n - noOfPrime);\n return x.multiply(y).mod(BigInteger.valueOf(MOD)).intValue();\n }\n\n public static BigInteger factorial(int n) {\n BigInteger fac = BigInteger.ONE;\n for (int i = 2; i <= n; i++) {\n fac = fac.multiply(BigInteger.valueOf(i));\n }\n return fac.mod(BigInteger.valueOf(MOD));\n }\n```\n\n
51
8
['Java']
7
prime-arrangements
[Java/Python 3] two codes each, count only primes then compute factorials for both w/ analysis.
javapython-3-two-codes-each-count-only-p-1tj1
compute (# of primes)! * (# of composites)!\n\nMethod 1: judge each number by dividing all possible factors\n\nJava\n\n public int numPrimeArrangements(int n
rock
NORMAL
2019-09-01T04:07:56.930690+00:00
2020-01-28T05:54:26.825023+00:00
5,810
false
compute (# of primes)! * (# of composites)!\n\n**Method 1: judge each number by dividing all possible factors**\n\n**Java**\n```\n public int numPrimeArrangements(int n) {\n int cnt = 1; // # of primes, first prime is 2.\n outer:\n for (int i = 3; i <= n; i += 2) { // only odd number could be a prime, if i > 2.\n for (int factor = 3; factor * factor <= i; factor += 2)\n if (i % factor == 0)\n continue outer;\n ++cnt;\n }\n long ans = 1;\n for (int i = 1; i <= cnt; ++i) // (# of primes)!\n ans = ans * i % 1_000_000_007;\n for (int i = 1; i <= n - cnt; ++i) // (# of non-primes)!\n ans = ans * i % 1_000_000_007;\n return (int)ans;\n }\n```\n\n----\n\n**Python 3**\n\n```\n def numPrimeArrangements(self, n: int) -> int:\n cnt = 1 # number of primes, first prime is 2.\n for i in range(3, n + 1, 2): # only odd number could be a prime, if i > 2.\n factor = 3\n while factor * factor <= i:\n if i % factor == 0:\n break \n factor += 2 \n else:\n cnt += 1 \n ans = 1\n for i in range(1, cnt + 1): # (number of primes)!\n ans *= i \n for i in range(1, n - cnt + 1): # (number of non-primes)!\n ans *= i\n return ans % (10**9 + 7)\n```\nWith Python lib, we can replace the last 6 lines of the above code by the follows:\n```\n return math.factorial(cnt) * math.factorial(n - cnt) % (10**9 + 7)\n```\n\n----\n\n**Analysis:**\n\nFor each outer iteration, inner loop cost O(n ^ 0.5).\n\nTime: O(n ^ (3/2)), space: O(1).\n\n----\n\n**Method 2: Sieve - mark all composites based on known primes**\n\n1. Initially, the only know prime is 2; \n2. Mark the prime, prime + 1, prime + 2, ..., times of current known primes as composites.\n\nObviouly, **each time the algorithm runs the inner for loop, it always uses a new prime factor `prime` and also `times` starts with `prime`**, which guarantees there is no repeated composites marking and hence very time efficient.\n\n**Java:**\n\n```\n public int numPrimeArrangements(int n) {\n boolean[] composites = new boolean[n + 1];\n for (int prime = 2; prime * prime <= n; ++prime)\n for (int cmpst = prime * prime; !composites[prime] && cmpst <= n; cmpst += prime)\n composites[cmpst] = true;\n long cnt = IntStream.rangeClosed(2, n).filter(i -> !composites[i]).count();\n return (int)LongStream.concat(LongStream.rangeClosed(1, cnt), LongStream.rangeClosed(1, n - cnt))\n .reduce(1, (a, b) -> a * b % 1_000_000_007);\n }\n```\n\n----\n\n**Python 3:**\n\n```\n def numPrimeArrangements(self, n: int) -> int:\n primes = [True] * (n + 1)\n for prime in range(2, int(math.sqrt(n)) + 1):\n if primes[prime]:\n for composite in range(prime * prime, n + 1, prime):\n primes[composite] = False\n cnt = sum(primes[2:])\n return math.factorial(cnt) * math.factorial(n - cnt) % (10**9 + 7)\n```\n\n**Analysis:**\n\nTime: O(n * log(logn)), space: O(n).\nFor time complexity analysis in details, please refer to [here](https://en.m.wikipedia.org/wiki/Sieve_of_Eratosthenes).\n\n----\n\n**Brief Summary:**\nMethod 1 and 2 are space and time efficient respectively.
32
3
[]
7
prime-arrangements
on the fly
on-the-fly-by-stefanpochmann-3yl5
Instead of counting and then computing factorials and their product, just compute the product directly while counting.\n\n public int numPrimeArrangements(in
stefanpochmann
NORMAL
2019-11-28T00:09:31.796771+00:00
2019-11-28T00:09:31.796821+00:00
2,186
false
Instead of counting and then computing factorials and their product, just compute the product directly while counting.\n```\n public int numPrimeArrangements(int n) {\n int[] non = new int[n+1];\n int[] cnt = {0, 1};\n long res = 1;\n for (int i=2; i<=n; i++) {\n if (non[i] == 0)\n for (int m=i*i; m<=n; m+=i)\n non[m] = 1;\n res = res * ++cnt[non[i]] % 1_000_000_007;\n }\n return (int) res;\n }\n```
28
3
[]
4
prime-arrangements
Detailed Explanation using Sieve
detailed-explanation-using-sieve-by-just-v4st
Intuition\n First, count all the primes from 1 to n using Sieve. Remember to terminate the outer loop at sqrt(n).\n Next , iterate over each positon and get the
just__a__visitor
NORMAL
2019-09-01T05:11:44.651765+00:00
2019-09-01T05:16:24.861375+00:00
2,309
false
# Intuition\n* First, count all the primes from 1 to **n** using **Sieve**. Remember to terminate the outer loop at **sqrt(n)**.\n* Next , iterate over each positon and get the count of prime positions, call it `k`.\n* So, for the `k` prime numbers, we have limited choice, we need to arrange them in `k` prime spots.\n* For the `n-k` non prime numbers, we also have limited choice. We need to arrange them in `n-k` non prime spots.\n* Both the events are indepent, so the total ways would be product of them.\n* Number of ways to arrange `k` objects in `k` boxes is `k!`.\n* Use the property that `(a*b) %m = ( (a%m) * (b%m) ) % m`.\n\n```\nclass Solution\n{\npublic:\n int numPrimeArrangements(int n);\n};\n\nint Solution :: numPrimeArrangements(int n)\n{\n vector<bool> prime(n + 1, true);\n prime[0] = false;\n prime[1] = false;\n \n for(int i = 2; i <= sqrt(n); i++)\n {\n if(prime[i])\n for(int factor = 2; factor*i <= n; factor++)\n prime[factor*i] = false;\n }\n \n int primeIndices = 0;\n for(int i = 1; i <= n; i++)\n if(prime[i])\n primeIndices++;\n \n int mod = 1e9 + 7, res = 1;\n\t\n for(int i = 1; i <= primeIndices; i++)\n res = (1LL*res*i) % mod;\n for(int i = 1; i<= (n-primeIndices); i++)\n res = (1LL*res*i) % mod;\n \n return res;\n \n}\n```
19
5
[]
3
prime-arrangements
[Python] Sieve of Eratosthenes
python-sieve-of-eratosthenes-by-cenkay-d4lu
\nclass Solution:\n def numPrimeArrangements(self, n: int) -> int:\n prime = [True for _ in range(n + 1)]\n p = 2\n while p * p <= n:\n
cenkay
NORMAL
2019-09-01T06:00:10.129241+00:00
2019-09-01T06:01:16.318537+00:00
1,978
false
```\nclass Solution:\n def numPrimeArrangements(self, n: int) -> int:\n prime = [True for _ in range(n + 1)]\n p = 2\n while p * p <= n:\n if prime[p]:\n for i in range(p * p, n + 1, p):\n prime[i] = False\n p += 1\n primes = sum(prime[2:])\n return math.factorial(primes) * math.factorial(n - primes) % (10 ** 9 + 7)\n```\n* Cheat\n```\nclass Solution:\n def numPrimeArrangements(self, n: int) -> int:\n primes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97]\n cnt = bisect.bisect(primes, n)\n return math.factorial(cnt) * math.factorial(n - cnt) % (10 ** 9 + 7)\n```\n
18
0
[]
1
prime-arrangements
C++ 7 line 0ms
c-7-line-0ms-by-sanzenin_aria-5lmj
```\n int numPrimeArrangements(int n) {\n static const vector primes = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97}; \n
sanzenin_aria
NORMAL
2019-11-22T02:38:53.851780+00:00
2019-11-22T02:40:10.259038+00:00
1,883
false
```\n int numPrimeArrangements(int n) {\n static const vector<int> primes = {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97}; \n const int k = upper_bound(primes.begin(), primes.end(), n) - primes.begin();\n const auto mod = (long long)1e9 + 7;\n long long res = 1;\n for(int i = 2; i<=k; i++) {res*=i; res%=mod;}\n for(int i = 2; i<=n-k; i++) {res*=i; res%=mod;}\n return res;\n }
16
3
[]
2
prime-arrangements
C++: Faster 100% with explanation
c-faster-100-with-explanation-by-andnik-c1e8
Algorithm is simple (Upvotes are appreciated):\n1. Calculate how many numbers [1..n] are prime numbers\nSince indexes are counted from 1 then all prime numbers
andnik
NORMAL
2020-02-18T15:27:10.594162+00:00
2020-02-18T15:27:10.594213+00:00
1,694
false
Algorithm is simple (**Upvotes are appreciated**):\n1. Calculate how many numbers `[1..n]` are prime numbers\nSince indexes are counted from `1` then all prime numbers are initially on their prime indexes.\nMeaning, number of prime numbers == number of prime indexes.\n2. Calculate how many not prime numbers: `n - count_of_prime_numbers`.\n3. Result would be: `permutations_of_all_prime_numbers_on_their_positions * permutations_of_all_not_prime_numbers_on_their_positions`.\n\nFormula for permutations count is simple, it\'s Factorial.\nSo if **a** is count of all prime numbers and **b** count of other numbers, then the result is:\n```\nreturn factorial(a) * factorial(b) % mod;\n// by init conditions mod == 10^9 + 7 == 1000000007\n```\n\nThe problem with the task is that max factorial we need to count is `75!` and it\'s waaaaay bigger than `ULONG_MAX`. **What to do?**\n\nRemember that `(a * b) mod c` is the same as `((a mod c) * (b mod c)) mod c` ? (check out [Properties of Modular Arithmetics](https://en.wikipedia.org/wiki/Modular_arithmetic#Properties))\n\nWe can use this rule to calculate Factorial: if value becomes bigger than `1000000007` we get the rest of devision on `1000000007`.\n\nThat\'s it!\n\nBut if we want to **achieve 0ms runtime** than we need to think that we calculate Factorial for **2 numbers** and most likely **one number is less than another**.\nWe can calculate **Factorial for smaller number** and then calculate Factorial for **second one**, but starting with **already calculated previous** value and not from `1` again.\n\n**Check out my code:**\n\n```\nclass Solution {\n const long mod = 1000000007;\n long factorial(int n, int prime = 2, long start = 1) {\n long a = start;\n for (int i = prime; i <= n; i++) {\n a *= i;\n if (a >= mod) a %= mod;\n }\n return a;\n }\npublic:\n int numPrimeArrangements(int n) {\n int primes[] {2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97};\n int i = 0;\n for (; i < 25 && primes[i] <= n; i++);\n int minNum = i, rest = n - i;\n if (n < (i << 1)) swap(minNum, rest);\n \n long a = factorial(minNum), b = factorial(rest, minNum + 1, a);\n return (int)(a * b % mod);\n }\n};\n```
9
3
['C']
1
prime-arrangements
Python 3 solution (100% faster and 100% less memory)
python-3-solution-100-faster-and-100-les-5fs7
the n-tuple can be bifurcated into two collections: primes and not primes. Since each element is unique - each collection\'s number of combinations is the fact
coltmac
NORMAL
2019-09-01T04:08:23.222529+00:00
2019-09-01T05:23:43.200265+00:00
1,699
false
the n-tuple can be bifurcated into two collections: primes and not primes. Since each element is unique - each collection\'s number of combinations is the factorial of its length. Multiply these two together since each representation in each collection (prime and not prime) can be arranged with all possible representations from the other collection.\n```\nfrom math import factorial\n\nclass Solution:\n def numPrimeArrangements(self, n: int) -> int:\n primes = [2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97]\n num_primes = len([x for x in primes if x <= n]) #cleaned up per comment\n return ( factorial(num_primes) * factorial(n - num_primes) ) % (10**9 + 7)\n```\n\n*Note: since the problem says n <= 100, listing the primes is efficient.
8
1
['Python', 'Python3']
2
prime-arrangements
C++ Simple Solution (beats all)
c-simple-solution-beats-all-by-rexagod-u0ut
\nclass Solution {\n int mod=1e9+7;\n int nop(int n) {\n int c=0, flag=false;\n for(int i=2; i<=n; i++) {\n for(int j=2; j*j<=i;
rexagod
NORMAL
2020-08-02T12:54:54.103151+00:00
2020-08-02T12:55:06.185394+00:00
981
false
```\nclass Solution {\n int mod=1e9+7;\n int nop(int n) {\n int c=0, flag=false;\n for(int i=2; i<=n; i++) {\n for(int j=2; j*j<=i; j++) {\n if(i%j==0) {\n flag = true;\n break;\n }\n }\n if(!flag)\n c++;\n else\n flag=false;\n }\n return c;\n }\n long long fact(int n) {\n if(n==0)\n return 1;\n return n*fact(n-1)%mod;\n }\npublic:\n int numPrimeArrangements(int n) {\n int p = nop(n);\n int c = n-p;\n long long x = fact(p)%mod*fact(c)%mod;\n return x%mod;\n }\n};\n```
7
0
['C']
1
prime-arrangements
Java BigInteger Solution only one time mod required
java-biginteger-solution-only-one-time-m-q294
Same as prime and non-prime number count idea, e.g in 1 to 5, we have 2, 3, 5 as 3 prime numbers, and 1, 4 as non-prime number, and prime numbers only should so
lampard08
NORMAL
2019-09-01T04:24:08.543630+00:00
2019-09-01T04:24:08.543664+00:00
912
false
Same as prime and non-prime number count idea, e.g in 1 to 5, we have 2, 3, 5 as 3 prime numbers, and 1, 4 as non-prime number, and prime numbers only should sort with prime numbers, non-prime numbers should only sort with non-prime numbers, so combinations should be 3! * 2! = 12, same for 100, we will have 25 prime numbers and 75 non-prime numbers, combinations should be 25! * 75!\ninstead of using long, use BigInteger only need to MOD once\n```\nimport java.math.BigInteger;\nclass Solution {\n public int numPrimeArrangements(int n) {\n if(n == 1) {\n return 1;\n }\n int primeNum = 0;\n for(int i = 2; i <= n; i++) {\n if(isPrime(i)) {\n primeNum++;\n }\n }\n int nonPrimeNum = n - primeNum;\n BigInteger a = totalComb(primeNum);\n BigInteger b = totalComb(nonPrimeNum);\n BigInteger result = a.multiply(b);\n BigInteger MOD = BigInteger.valueOf(1000000007);\n return result.mod(MOD).intValue();\n }\n \n private BigInteger totalComb(int n) {\n BigInteger result = BigInteger.valueOf(1);\n for(int i = 1; i <= n; i++) {\n result = result.multiply(BigInteger.valueOf(i));\n }\n return result;\n }\n \n private boolean isPrime(int n) {\n int count = 0;\n for(int i = 1; i <= n; i++) {\n if(n % i == 0) {\n count++;\n }\n if(count > 2) {\n return false;\n }\n }\n return true;\n }\n}\n```
6
0
[]
0
prime-arrangements
seive_of_erotosthenes C++
seive_of_erotosthenes-c-by-piyushb544-e6fk
class Solution {\npublic:\n\n int numPrimeArrangements(int n) {\n if(n==1){\n return 1;\n }\n vector arr(n+1,1);\n arr
piyushb544
NORMAL
2021-09-07T09:25:00.112056+00:00
2021-09-07T09:25:00.112094+00:00
533
false
class Solution {\npublic:\n\n int numPrimeArrangements(int n) {\n if(n==1){\n return 1;\n }\n vector<int> arr(n+1,1);\n arr[0] = 0;\n arr[1] = 0;\n int count = 0;\n for(int i = 2; i<=sqrt(n); i++){\n for(int j = i*i; j<=n; j+=i){\n if(arr[j]==1){\n arr[j] = 0;\n }\n }\n }\n \n for(int i = 0; i<arr.size(); i++){\n if(arr[i]==1){\n count++;\n }\n }\n long long int answer = 1;\n int reverse = n - count;\n \n while(reverse!=1){\n answer = answer*reverse%1000000007;\n answer%1000000007;\n reverse--;\n }\n while(count!=1){\n answer = answer*count%1000000007;\n answer%1000000007;\n count--;\n }\n return answer;\n }\n};\nPlease Upvote
5
0
['C']
0
prime-arrangements
C++ 0 ms solution w/ optimized sieve
c-0-ms-solution-w-optimized-sieve-by-guc-6vfy
Algorithm Explanation: \nAssume we have up to n.\nThere are k primes <= n , so k prime slots. We have k! ways to assign all prime numbers.\nWe have another (n-k
guccigang
NORMAL
2020-03-10T17:45:29.196511+00:00
2020-03-10T17:45:50.088834+00:00
538
false
Algorithm Explanation: \nAssume we have up to `n`.\nThere are `k` primes `<= n` , so `k` prime slots. We have `k!` ways to assign all prime numbers.\nWe have another `(n-k)` slots remaining. We have `(n-k)!` ways of assigning the rest of the numbers.\nIn total, there are `(n-k)! * k!` possible permutations.\n\nThe number of primes (`k`) is calculated using sieve of E. (Can\'t remember his name). To optimize, we skip all even numbers, and start at `3`. For count we just add `2` after everything.\n\nRun-time is `O(n)`. We need to go through half of the numbers using seive, and need to multiply `n` numbers together.\n\n```\nclass Solution {\npublic:\n int numPrimeArrangements(int n) {\n bitset<100> primes;\n primes.set();\n for(int i = 3, stop = (n+1)>>1; i <= stop; i += 2)\n if(primes[i]) \n for(int j = 2; i*j <= n; ++j) primes[i*j] = false;\n\t\t\t\t\n int64_t k = 1, res = 1;\n for(int i = 3; i <= n; i += 2) k += primes[i];\n for(int i = 2, stop = n-k; i <= stop; ++i) res = (res * i) % MOD;\n for(int i = 2; i <= k; ++i) res = (res * i) % MOD;\n return res;\n }\n static const int MOD = 1e9+7;\n};\n```
4
0
[]
0
prime-arrangements
[C++] Beats 100% Time 100% Space No Sieve Of Eratosthenes
c-beats-100-time-100-space-no-sieve-of-e-w60x
\nclass Solution {\npublic:\n int numPrimeArrangements(int n) {\n const long MOD = 1e9 + 7;\n int count = 0;\n vector<long> f(n + 1, 1);
gagandeepahuja09
NORMAL
2019-12-30T14:39:02.634293+00:00
2019-12-30T14:39:02.634326+00:00
433
false
```\nclass Solution {\npublic:\n int numPrimeArrangements(int n) {\n const long MOD = 1e9 + 7;\n int count = 0;\n vector<long> f(n + 1, 1);\n for(int i = 2; i <= n; i++) {\n f[i] = f[i - 1] * i;\n f[i] %= MOD;\n }\n for(int p = 2; p <= n; p++) {\n bool isprime = true;\n for(int i = 2; i * i <= p; i++) {\n if(p % i == 0) {\n isprime = false;\n break;\n }\n }\n if(isprime)\n count++;\n }\n cout << count << endl;\n return (int)(f[count] % MOD * f[n - count] % MOD);\n }\n};\n```
4
0
[]
2
prime-arrangements
JavaScript Answer passed, but have a number precision issue?
javascript-answer-passed-but-have-a-numb-gkmh
I came up with the following code during contest: \n\n/**\n * @param {number} n\n * @return {number}\n */\nvar numPrimeArrangements = function(n) {\n let how
jiayi4
NORMAL
2019-09-01T04:31:18.499278+00:00
2019-09-01T04:31:18.499317+00:00
339
false
I came up with the following code during contest: \n```\n/**\n * @param {number} n\n * @return {number}\n */\nvar numPrimeArrangements = function(n) {\n let howManyPrime = 0;\n let primes = 1;\n let nonePrimes = 1;\n for (let i = 1; i <= n; i++) {\n howManyPrime = isPrime(i) ? ++howManyPrime : howManyPrime;\n }\n for (let i = howManyPrime; i >= 1; i--) {\n primes = i * primes % (10**9 + 7);\n }\n for (let i = n - howManyPrime; i >= 1; i--) {\n nonePrimes = i * nonePrimes % (10**9 + 7);\n }\n let result = primes * nonePrimes % (10**9 + 7);\n return result;\n};\n\nfunction isPrime(value) {\n for(var i = 2; i < value; i++) {\n if(value % i === 0) {\n return false;\n }\n }\n return value > 1;\n}\n```\n\nHowever the answer is not right, but very close, like for `input=100`, correct answer should be `682289015` my answer is `682289019`\n\nSo I tweaked my logic a little bit:\n```\n/**\n * @param {number} n\n * @return {number}\n */\nvar numPrimeArrangements = function(n) {\n let howManyPrime = 0;\n let primes = 1;\n let nonePrimes = 1;\n for (let i = 1; i <= n; i++) {\n howManyPrime = isPrime(i) ? ++howManyPrime : howManyPrime;\n }\n console.log(howManyPrime);\n for (let i = howManyPrime; i >= 1; i--) {\n primes = i * primes % (10**9 + 7);\n }\n for (let i = n - howManyPrime; i >= 1; i--) {\n\t// !!!! Here is the change;\n primes = i * primes % (10**9 + 7);\n }\n return primes;\n};\n\nfunction isPrime(value) {\n for(var i = 2; i < value; i++) {\n if(value % i === 0) {\n return false;\n }\n }\n return value > 1;\n}\n\n```\nInstead doing facotial twice, I continued to do mutiplication on the existing `primes` and the answer is correct and passed tests\n\nSo the logic is totally the same. but one is wrong, the other is right. My guess is something is wrong with JS\'s big number precision, but I don\'t know exactly what went wrong. Anyone has idea? Thanks!
4
0
[]
2
prime-arrangements
Java Solution 100 %
java-solution-100-by-jiaxichen-e7a7
\nclass Solution {\n public int numPrimeArrangements(int n) {\n if(n < 2){\n return 1;\n }\n long res = 1;\n int prime
jiaxichen
NORMAL
2021-05-10T13:38:24.820519+00:00
2021-05-10T13:38:24.820570+00:00
612
false
```\nclass Solution {\n public int numPrimeArrangements(int n) {\n if(n < 2){\n return 1;\n }\n long res = 1;\n int prime = 1;\n int notPrime = 1;\n for(int i = 3; i <= n; i++){\n if(isPrime(i)){\n prime++;\n }else{\n notPrime++;\n }\n }\n for(int i = prime; i > 0; i--){\n res *= i;\n res %= 1000000007;\n }\n for(int i = notPrime; i > 0; i--){\n res *=i;\n res %= 1000000007;\n }\n return (int)res; \n }\n public boolean isPrime(int num){\n for(int i = 2; i <= num / 2; i++){\n if(num % i == 0){\n return false;\n }\n }\n return true;\n }\n}\n```
3
0
['Java']
0
prime-arrangements
C++ Solution with Explanation
c-solution-with-explanation-by-claytonjw-2gl9
Synopsis:\n Count the primes from 1 to n inclusive\n The answer is all prime permutations multiplied by all non-prime permutations\n( ie. the factorial of the a
claytonjwong
NORMAL
2019-09-06T16:40:16.888531+00:00
2019-09-06T16:40:16.888573+00:00
642
false
**Synopsis:**\n* Count the primes from 1 to n inclusive\n* The answer is all prime permutations multiplied by all non-prime permutations\n( ie. the factorial of the amount of primes multiplied by the factorial of the amount of non-primes )\n\n**Solution:**\n```\nclass Solution {\npublic:\n constexpr static auto MOD = static_cast<int>(1e9+7);\n int numPrimeArrangements(int n, int primes=1, long long ans=1) { // 2 is the first prime\n for (auto i=3; i <= n; ++i) {\n if (isPrime(i)) {\n ++primes;\n }\n }\n for (auto i=1; i <= primes; ++i) { // all permutations of primes == factorial of primes\n ans = ans * i % MOD;\n }\n for (auto i=1; i <= n - primes; ++i) { // all permutations of non-primes == factorial of non-primes\n ans = ans * i % MOD;\n }\n return ans;\n }\nprivate:\n bool isPrime(int n) {\n for (auto i=2; i*i <= n; ++i) {\n if (n % i == 0) {\n return false;\n }\n }\n return true;\n }\n};\n```
3
0
[]
0
prime-arrangements
JavaScript Dynamic Programming and BigInt()
javascript-dynamic-programming-and-bigin-f4e7
js\nvar numPrimeArrangements = function(n) {\n let count = 0;\n const MOD = BigInt(1e9 + 7);\n const factorials = [1n]\n for(let i=1; i<=n; i++) fac
0618
NORMAL
2019-09-04T02:21:43.590070+00:00
2019-09-04T02:21:43.590109+00:00
181
false
```js\nvar numPrimeArrangements = function(n) {\n let count = 0;\n const MOD = BigInt(1e9 + 7);\n const factorials = [1n]\n for(let i=1; i<=n; i++) factorials[i] = BigInt(factorials[i-1]*BigInt(i)%MOD);\n \n function isPrime(m){\n for(let i=2; i*i<=m; i++){\n if(m%i === 0) return false;\n }\n return true;\n }\n \n for(let i=2; i<=n; i++){\n count += isPrime(i)\n }\n \n return factorials[count]*factorials[n-count]%(MOD);\n};\n```
3
0
[]
0
prime-arrangements
Java sum of permutations of primes and non-primes
java-sum-of-permutations-of-primes-and-n-anxg
We count the number of primes <= n.\nThe total number of arragements = total number of permutations of primes + total number of permutations of non-primes\n\n\n
sun_wukong
NORMAL
2019-09-01T04:08:39.083508+00:00
2019-09-01T04:08:39.083557+00:00
675
false
We count the number of primes `<= n`.\nThe total number of arragements = total number of permutations of primes + total number of permutations of non-primes\n\n```\nclass Solution {\n public int numPrimeArrangements(int n) {\n int m = countPrimes(n+1), M = 1000000007;\n long count = 1;\n for (int i = m; i > 0; i--) {\n count = (count*i)%M;\n }\n for (int i = n-m; i > 0; i--) {\n count = (count*i)%M;\n }\n return (int)count;\n }\n \n private int countPrimes(int n) {\n boolean[] isPrime = new boolean[n];\n for (int i = 2; i < n; i++) {\n isPrime[i] = true;\n }\n \n for (int i = 2; i*i < n; i++) {\n if (!isPrime[i]) {\n continue;\n }\n for (int j = i*i; j < n; j += i) {\n isPrime[j] = false;\n }\n }\n \n int count = 0;\n for (int i = 2; i < n; i++) {\n if (isPrime[i]) {\n count++;\n }\n }\n return count;\n }\n}\n```
3
1
[]
0