Wordakshari Program: Validate a Word Chain in C, Java and Python
Solve the Wordakshari programming problem: validate a word chain where each word begins with the last letter of the previous one. Code in C, Java, and Python.
Wordakshari is a word-chain programming problem where each word in a sequence must start with the last letter of the word before it.
The game comes from Indian social culture, and its programming version is a direct string-matching exercise, a staple of the character-level problems that show up in campus placement coding rounds.
What Is Wordakshari?
Wordakshari takes its structure from Antakshari, the call-and-response game that has been a fixture of Indian family gatherings for decades. In Antakshari, a team must begin a film song using the last syllable of the previous team’s song. In Wordakshari, the unit shifts from syllable to letter: say “architect” and the next player must respond with a word that starts with “t”. Say “tailor” and the next word must start with “r”.
Three rules govern the game:
- The first word can begin with any letter.
- Every word after the first must begin with the last letter of the word before it.
- No word may be repeated.
The programming version formalises the second rule: given a list of words, print the longest valid prefix of that list. A “valid prefix” is the unbroken chain from the first word up to the last word that satisfies the rule. The moment a word breaks the pattern, the output stops.
Problem Statement and Input Format
The input arrives line by line. Words continue until the sentinel string #### signals the end of input. The program must output the valid chain, stopping at the first word that violates the starting-letter rule.
Sample input:
architect
tailor
referee
electrician
nurse
blacksmith
####
Expected output:
architect
tailor
referee
electrician
nurse
Walk through the sample step by step:
architectends witht.tailorstarts witht. Valid — printtailor.tailorends withr.refereestarts withr. Valid — printreferee.refereeends withe.electricianstarts withe. Valid — printelectrician.electricianends withn.nursestarts withn. Valid — printnurse.nurseends withe.blacksmithstarts withb. Chain broken — stop.
The output includes every word from architect through nurse. The word blacksmith is not printed because it breaks the rule.
Note that the first word is always printed. The chain check begins from the second word onward.
Algorithm to Validate the Chain
The algorithm is a single linear pass over the word list:
- Step 1: Read all words into a list, stopping when
####is encountered. - Step 2: Print the first word unconditionally.
- Step 3: For each word at index
i(starting from 1), compare the last character of wordi-1with the first character of wordi. - Step 4: If they match, print word
iand continue to the next pair. - Step 5: If they do not match, stop. Print nothing further.
Each comparison reads exactly two characters: the last character of the previous word and the first character of the current word. The list is traversed once. Total time: O(n x m), where n is the number of words and m is the average word length (the cost of reading each word into memory). Space is O(n x m) for storing the word list.
No sorting, no hashing, no secondary data structure is required.
Code in C, Java and Python
C
#include <stdio.h>
#include <string.h>
int main() {
char words[100][100];
int count = 0;
while (scanf("%s", words[count]) == 1) {
if (strcmp(words[count], "####") == 0) break;
count++;
}
printf("%s\n", words[0]);
for (int i = 1; i < count; i++) {
int len = strlen(words[i - 1]);
if (words[i - 1][len - 1] == words[i][0]) {
printf("%s\n", words[i]);
} else {
break;
}
}
return 0;
}
Java
import java.util.ArrayList;
import java.util.Scanner;
public class Wordakshari {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
ArrayList<String> words = new ArrayList<>();
String word;
while (sc.hasNext()) {
word = sc.next();
if (word.equals("####")) break;
words.add(word);
}
System.out.println(words.get(0));
for (int i = 1; i < words.size(); i++) {
String prev = words.get(i - 1);
if (prev.charAt(prev.length() - 1) == words.get(i).charAt(0)) {
System.out.println(words.get(i));
} else {
break;
}
}
}
}
Python
words = []
while True:
w = input()
if w == "####":
break
words.append(w)
print(words[0])
for i in range(1, len(words)):
if words[i - 1][-1] == words[i][0]:
print(words[i])
else:
break
The Python solution is the most compact. words[i - 1][-1] is Python’s idiomatic way to read the last character of a string without an explicit len() call. All three implementations produce identical output on the sample input.
For more string exercises and basic programs to practise on, see FACE Prep’s Python basic programs guide.
String Problems in Campus Placement Tests
String manipulation is a core topic in the coding sections of Indian campus placement tests. AMCAT automata rounds, CoCubes online coding tests, and HackerEarth-based campus drives all include string problems. The difficulty ranges from simple reversal and palindrome checks to chain-validation patterns like Wordakshari.
Why does this appear in placement coding rounds? Coding test platforms at companies like TCS, Cognizant, and Capgemini typically set two to three problems to be solved in 30 to 45 minutes. String problems are common because they test whether a candidate can think about individual characters rather than just calling library functions blindly. A candidate who understands strlen in C, charAt in Java, and index notation in Python is demonstrating that they understand how strings are stored and accessed.
The Wordakshari problem specifically tests four skills that appear in isolation across other campus problems:
- Reading and storing a variable-length list of strings from stdin.
- Accessing the first and last characters of a string.
- Iterating over a list with a conditional early-exit.
- Handling a sentinel-terminated input stream rather than a fixed-count loop.
The vowel or consonant checker is another character-classification problem from the same category: the core pattern is “read one character, compare it against a condition.” Both problems are solvable in under 20 lines.
For the implementation details behind the string functions used in the solutions above, specifically how strlen allocates, how Java’s charAt maps to memory, and how Python’s negative indexing works, the GeeksforGeeks String Data Structure guide covers the underlying mechanics.
String problems at this difficulty level are solvable in 10 to 15 minutes with practice. The challenge is not the algorithm. It is reading the problem statement carefully, identifying the sentinel value, and writing the early-exit correctly under time pressure.
The character-by-character logic in Wordakshari mirrors what language models do when they tokenise text. Models process byte sequences millions of characters long, applying character-level operations at scale. If that parallel prompted a question about how LLMs work internally, TinkerLLM is the entry point: ₹299 for a month of hands-on experiments with real language models, no prior AI background required.
Primary sources
Frequently asked questions
What is the Wordakshari game?
Wordakshari is a word-chain game similar to Antakshari. The first player says any word; the next must say a word starting with the last letter of the previous word. No word can be repeated.
What does the Wordakshari program output?
The program prints the longest valid prefix of a given word list where each consecutive pair satisfies the chain rule: each new word must start with the last letter of the word before it.
What is the time complexity of the Wordakshari algorithm?
The algorithm runs in O(n x m) time, where n is the number of words and m is the average word length. The dominant cost is reading the first and last characters of each word.
Can words be repeated in Wordakshari?
No. Repeating a word is against the rules. The standard programming problem assumes all input words are distinct, so no deduplication step is needed in the basic validator.
Where do string chain problems like Wordakshari appear in placement tests?
String chain and chain-validation problems appear in AMCAT automata sections, CoCubes coding rounds, and HackerEarth-based campus tests at companies including TCS, Cognizant, and Capgemini.
A self-paced playground for building with LLMs.
TinkerLLM is FACE Prep's sister property. A guided environment for shipping real LLM applications, the kind of project that earns a paragraph on your resume, not a line.
Try TinkerLLM (₹299 launch)