Unique String Program in Java (No Repeated Characters)

⚑ Direct Answer & Key Takeaway

A Unique String contains no repeated characters anywhere in the word or sentenceβ€”for example, `"COMPUTER"` is unique, and `"PROGRAM"` is not because `'R'` appears twice. In ICSE Java, normalize case with `toUpperCase()`, then either compare every pair of indices `(i, j)` with `j = i + 1` in a nested `for` loop, or check `str.indexOf(ch) != str.lastIndexOf(ch)` inside a single loop.

1. Definition & Case-Sensitivity Rules in ICSE Questions

In CISCE Java questions, a string qualifies as a Unique String only when no letter occurs more than once. Standard exam definitions treat uppercase and lowercase pairs such as `'M'` and `'m'` in `"Madam"` as duplicates, making `raw.trim().toUpperCase()` an essential first step. If the prompt accepts multi-word phrases rather than single words, skipping spaces via `if (c1 == ' ') continue;` ensures multiple word separators do not falsely trigger a duplicate flag. Words like `"COMPUTER"`, `"BLUEJ"`, and `"LAMP"` pass, while `"INDIA"` and `"SUCCESS"` fail.

  • "COMPUTER", "DERMATOGLYPHICS", and "LAMP" are classic ICSE Unique Strings.
  • Normalize with toUpperCase() so 'M' and 'm' in "Madam" count as a repeated letter.
  • Skip whitespace (c1 == ' ') when testing multi-word phrases rather than single words.

2. Nested Loop Pairwise Check vs. indexOf/lastIndexOf Trick

Two distinct techniques solve Unique String checks cleanly. The standard nested-loop algorithm runs an outer index `i` from `0` to `len - 2` and an inner index `j` from `i + 1` to `len - 1`. Whenever `str.charAt(i) == str.charAt(j)`, `isUnique` flips to `false` and the loops exit early. Starting `j` at `i + 1` avoids self-comparison (`i == j`) and eliminates duplicate mirror checks. Alternatively, a single-loop trick evaluates `str.indexOf(ch) != str.lastIndexOf(ch)`β€”if first and last occurrence indices differ, the character repeats.

  • Starting the inner loop at j = i + 1 prevents false duplicates from comparing str.charAt(i) with itself.
  • Adding && isUnique to the outer loop header stops both loops cleanly once a duplicate appears.
  • str.indexOf(ch) != str.lastIndexOf(ch) detects duplicates in a single loop without extra arrays.
  • For single-word alphabet checks, a boolean seen[] = new boolean[26] array achieves linear O(n) speed.

3. Dry Run Trace on "COMPUTER" vs. "APPLE"

Tracing `"COMPUTER"` (length `8`) shows why the outer loop stops at `len - 2` (`i < 7`): once index `6` (`'E'`) checks against index `7` (`'R'`), every unordered pair has already been tested. All `28` pairs miss, keeping `isUnique = true`. By contrast, trace `"APPLE"` (`len = 5`): at `i = 0`, `'A'` checks `'P','P','L','E'` with zero matches. At `i = 1`, `'P'` immediately collides with `j = 2` (`'P'`), setting `isUnique = false`, breaking out of the inner loop, and exiting the outer loop via `&& isUnique` before reaching `'L'`.

  • Early termination via break and && isUnique avoids wasted comparisons after the first match.
  • A single-character input like "A" has zero pairs (0 < 0 is false) and is correctly marked unique.
  • Checking len == 0 separately gives a polite message instead of calling an empty input "unique".

4. UniqueString.java β€” Nested Loop ICSE Solution

import java.util.*;

public class UniqueString {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.print("Enter a word or string: ");
        String raw = sc.nextLine();

        String str = raw.trim().toUpperCase();
        int len = str.length();
        boolean isUnique = true;

        for (int i = 0; i < len - 1 && isUnique; i++) {
            char c1 = str.charAt(i);
            if (c1 == ' ') {
                continue;
            }
            for (int j = i + 1; j < len; j++) {
                char c2 = str.charAt(j);
                if (c1 == c2) {
                    isUnique = false;
                    break;
                }
            }
        }

        if (len == 0) {
            System.out.println("Empty string entered.");
        } else if (isUnique) {
            System.out.println("\"" + raw + "\" is a Unique String.");
        } else {
            System.out.println("\"" + raw + "\" is NOT a Unique String.");
        }
        sc.close();
    }
}

Verified Console / Dry-Run Output:

Enter a word or string: Computer
"Computer" is a Unique String.

5. CISCE Variable Description Table (VDT) & Dry Run

VariableData TypeExam Purpose & Sample Value
rawStringStores original user input; sample: "Computer"
strStringTrimmed uppercase copy for case-insensitive check: "COMPUTER"
lenintStores length of normalized string; sample: 8
isUniquebooleanTracks uniqueness; stays true for "COMPUTER", false if duplicate found
iintOuter loop index (0 to len - 2) selecting reference character c1
jintInner loop index (i + 1 to len - 1) comparing c2 against c1
🎯 1-on-1 Live Mentorship & Free Study Kit

Master Nested Loops & String Flags Live

Build rock-solid dry-run speed for nested loops, Unique Strings, and Special Words with a dedicated 1-on-1 ICSE Java mentor.

πŸ’¬ WhatsApp Now
πŸ”’ Instant WhatsApp notes + free 60-min 1-on-1 trial session
Confirmed! Our Senior Mentor is sending your study kit & free 1-on-1 demo link on WhatsApp now.

6. Common Mistakes & Top Scorer Tips

  • Avoid Mistake: Starting the inner loop at j = 0 instead of j = i + 1, which compares str.charAt(0) with itself and marks every string as NOT unique.
  • Avoid Mistake: Breaking only out of the inner j loop while forgetting && isUnique in the outer loop header, wasting iterations after a duplicate is already found.
  • Avoid Mistake: Forgetting toUpperCase() before checking, causing words like "India" ('I' and 'i') to be mistakenly reported as unique.
  • Examiner / Mentor Tip: If an ICSE viva examiner asks for an O(n) single-loop version, show if (str.indexOf(ch) != str.lastIndexOf(ch)).
  • Examiner / Mentor Tip: Clarify whether spaces count as characters; adding if (c1 == ' ') continue; safely ignores spaces in phrases.
  • Examiner / Mentor Tip: Mention trim() in your VDT so accidental trailing spaces never cause false duplicate failures.

7. Interactive Concept Check Quiz

Question: In the nested-loop Unique String algorithm, why must the inner loop start at j = i + 1 instead of j = i?

8. Frequently Asked Questions

What is the difference between a Unique String and a Special Word in ICSE?
A Unique String has no repeated characters anywhere (like `"COMPUTER"` or `"LAMP"`). By contrast, a Special Word in ICSE starts and ends with the exact same letter (like `"WINDOW"` or `"LEVEL"`), regardless of whether intermediate letters repeat. Always read the board definition carefully before writing the loop.
Is "India" considered a Unique String in ICSE Java?
No. Under standard ICSE board conventions, character uniqueness ignores letter case, so `'I'` at index 0 and `'i'` at index 3 count as the same letter repeated twice. Converting the input via `toUpperCase()` before running comparisons ensures `"India"` is accurately reported as not unique.
Can I solve Unique String using only one loop instead of nested loops?
Yes! Inside a single `for` loop from `0` to `str.length() - 1`, fetch `ch = str.charAt(i)` and test `if (str.indexOf(ch) != str.lastIndexOf(ch))`. If a character appears twice, its first and last indices will differ, allowing you to set `isUnique = false` and `break` immediately.

Explore Related Lessons & Free Interactive Tools

Free 1-on-1 Session

Book a Free Demo Class