Sign in to devexcode.com with google.com

To continue, google.com will share your name, email address, and profile picture with this site. See this site's privacy policy.

830. Positions of Large Groups

String

Explanation

To solve this problem, we can iterate through the string and identify the intervals of consecutive characters that form large groups (groups with 3 or more characters). We can keep track of the start and end indices of each group and add the interval to the result if the group is large. Finally, we return the intervals sorted by the start index.

  • Start by initializing variables to track the start index and the current character.
  • Iterate through the string.
  • If the current character is different from the previous character, check if the group is large (end - start >= 2).
  • If the group is large, add the interval [start, end] to the result.
  • Update the start index and the current character.
  • After the loop, check the last group if it is large.
  • Return the sorted list of intervals.

Time complexity: O(n) where n is the length of the input string s. Space complexity: O(1) excluding the space for the output list.

class Solution {
    public List<List<Integer>> largeGroupPositions(String s) {
        List<List<Integer>> result = new ArrayList<>();
        int start = 0;
        char prevChar = s.charAt(0);
        
        for (int end = 1; end < s.length(); end++) {
            char currChar = s.charAt(end);
            if (currChar != prevChar) {
                if (end - start >= 2) {
                    result.add(Arrays.asList(start, end - 1));
                }
                start = end;
                prevChar = currChar;
            }
        }
        
        if (s.length() - start >= 3) {
            result.add(Arrays.asList(start, s.length() - 1));
        }
        
        return result;
    }
}

Code Editor (Testing phase)

Improve Your Solution

Use the editor below to refine the provided solution. Select a programming language and try the following:

  • Add import statement if required.
  • Optimize the code for better time or space complexity.
  • Add test cases to validate edge cases and common scenarios.
  • Handle error conditions or invalid inputs gracefully.
  • Experiment with alternative approaches to deepen your understanding.

Click "Run Code" to execute your solution and view the output. If errors occur, check the line numbers and debug accordingly. Resize the editor by dragging its bottom edge.