LeetCode: Reverse Words in a String

Problem statements:

Examples:

Constraints:

Edge Cases to Consider

Solution Approach:

Approach-1: In-place Reversal (Optimal) - T.C: O(N) & S.C: O(1)

Approach-2: Using StringBuilder to split and merge words

Solution:

Solution-1: Two Pointer approach [T.C: O(n) & S.C: O(1)]

        public String solution(String s) {
            if (s == null || s.isBlank()) return "";
            if (s.length() == 1) return s;

            char[] arr = s.toCharArray();

            // Step-1: Reverse entire string
            reverse(arr, 0, arr.length - 1);

            // step-2: reverse each word
            reverseWord(arr);

            // Step-3: clean spaces
            int len = cleanSpaces(arr);

            String res = new String(arr, 0, len);
            System.out.printf("Input : [%s] %nOutput: [%s] %n", s, res);
            return res;
        }

        public int cleanSpaces(char[] arr) {
            int l = 0, r = 0;
            while(r < arr.length) {
                while (r < arr.length && arr[r] == ' ') r++;
                while (r < arr.length && arr[r] != ' ') {
                    arr[l++] = arr[r++];
                }
                // Skip extra spaces between words
                while (r < arr.length && arr[r] == ' ') r++;
                if (r < arr.length) arr[l++] = ' ';
            }
            // Remove trailing space if it exists
            return (l > 0 && arr[l - 1] == ' ') ? l - 1 : l;
        }


        public void reverseWord(char[] arr) {
            int l = 0, r = 0;
            while(r < arr.length) {
                // Find start of the word
                while(l < arr.length && arr[l] == ' ') l++;
                if (l >= arr.length) break;

                // Find end of the word
                r = l;
                while (r < arr.length && arr[r] != ' ') r++;

                // reverse word
                if(l < r) reverse(arr, l, r - 1);

                //move to next word
                l = r;
            }
        }

        public void reverse(char[] arr, int start, int end) {
            while(start < end) {
                char temp = arr[start];
                arr[start++] = arr[end];
                arr[end--] = temp;
            }
        }

Solution-2: Using StringBuilder to split and merge words

      public static String reverseWords(String s) {
          StringBuilder sb = new StringBuilder();
          int right = s.length() - 1;

          while (right >= 0) {
              // Skip trailing spaces
              while (right >= 0 && s.charAt(right) == ' ') right--;
              if (right < 0) break;

              // Find start of the word
              int left = right;
              while (left >= 0 && s.charAt(left) != ' ') left--;

              // Append word
              sb.append(s, left + 1, right + 1).append(' ');

              // Move right pointer
              right = left;
          }

          // Remove last space
          return sb.length() > 0 ? sb.substring(0, sb.length() - 1) : "";
      }

Comparison with In-Place Approach

Approach Time Complexity Space Complexity Pros Cons
In-Place Reversal O(n) O(1) No extra space, efficient Complex implementation
StringBuilder Approach O(n) O(n) Simple, easy to understand Uses extra space

------ End ------