easy
0 views

Move M Words – End Reverse

Move the first M words to the end of a sentence in reverse order

Understand the Problem

Problem Statement

The program must accept a string S which contains N words and move the first M words to the last in the reverse order.

Constraints

  • M <= N <= 50
  • 10 <= Length of S <= 200
  • Input string contains exactly N words separated by single spaces
  • M is a positive integer

Examples

Example 1
Input
one two three four five
3
Output
four five three two one
Explanation

The first 3 words are 'one two three'. The remaining words are 'four five'. Moving the first 3 words to the end in reverse order gives: 'four five' + 'three two one' = 'four five three two one'

Solution

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int main() {
    char s[201];
    fgets(s, sizeof(s), stdin);
    
    int m;
    scanf("%d", &m);
    
    // Remove newline from fgets
    s[strcspn(s, "\n")] = 0;
    
    // Split string into words
    char *words[50];
    int word_count = 0;
    
    char *token = strtok(s, " ");
    while (token != NULL && word_count < 50) {
        words[word_count++] = token;
        token = strtok(NULL, " ");
    }
    
    // Print remaining words (from index m to end)
    for (int i = m; i < word_count; i++) {
        printf("%s ", words[i]);
    }
    
    // Print first m words in reverse order
    for (int i = m - 1; i >= 0; i--) {
        printf("%s ", words[i]);
    }
    
    return 0;
}
Time:O(N) where N is the number of words
Space:O(N) for storing the words array
Approach:

C Solution Explanation:

  1. Read the input string using fgets() and integer M using scanf()
  2. Remove the newline character from the string
  3. Use strtok() to split the string into words and store them in an array
  4. First loop: print words from index M to the end (remaining words)
  5. Second loop: print the first M words in reverse order (from M-1 down to 0)
  6. Each word is followed by a space for proper formatting

Visual Explanation

Loading diagram...