LeetCode 1933: Check if String Is Decomposable Into Value-Equal Substrings Solution
Master LeetCode problem 1933 (Check if String Is Decomposable Into Value-Equal Substrings), a easy challenge, with our optimized solutions in Java, C++, and Python. Explore detailed explanations, test your code in our interactive editor, and prepare for coding interviews.
1933. Check if String Is Decomposable Into Value-Equal Substrings
Problem Explanation
Explanation
To solve this problem, we need to check if a given string can be decomposed into substrings that are all value equal. We can achieve this by iterating through the string and counting the occurrences of each unique substring. If the count of any substring is not a multiple of the substring length, then the string cannot be decomposed into value-equal substrings.
Here is the algorithm:
- Create a hashmap to store the count of each unique substring.
- Iterate through the string with a sliding window of size equal to the length of the substrings.
- For each window, extract the substring and increment its count in the hashmap.
- If at any point, the count of a substring is not a multiple of its length, return false.
- If we reach the end of the string without any discrepancies, return true.
Time complexity: O(n) Space complexity: O(n)
Solution Code
class Solution {
public boolean isDecomposable(String s) {
Map<String, Integer> map = new HashMap<>();
int n = s.length();
for (int i = 0; i < n; i++) {
for (int len = 2; len <= 3; len++) {
if (i + len <= n) {
String sub = s.substring(i, i + len);
map.put(sub, map.getOrDefault(sub, 0) + 1);
}
}
}
for (int i = 0; i < n; i++) {
for (int len = 2; len <= 3; len++) {
if (i + len <= n) {
String sub = s.substring(i, i + len);
if (map.getOrDefault(sub, 0) % len != 0) {
return false;
}
}
}
}
return true;
}
}Try It Yourself
Loading code editor...
Related LeetCode Problems
Frequently Asked Questions
How to solve LeetCode 1933 (Check if String Is Decomposable Into Value-Equal Substrings)?
This page provides optimized solutions for LeetCode problem 1933 (Check if String Is Decomposable Into Value-Equal Substrings) in Java, C++, and Python, along with a detailed explanation and an interactive code editor to test your code.
What is the time complexity of LeetCode 1933 (Check if String Is Decomposable Into Value-Equal Substrings)?
The time complexity for LeetCode 1933 (Check if String Is Decomposable Into Value-Equal Substrings) varies by solution. Check the detailed explanation section for specific complexities in Java, C++, and Python implementations.
Can I run code for LeetCode 1933 on DevExCode?
Yes, DevExCode provides an interactive code editor where you can write, test, and run your code for LeetCode 1933 in Java, C++, or Python.