Bird
Raised Fist0
DSA Typescriptprogramming

How Strings Work Differently Across Languages in DSA Typescript - Step-by-Step

Choose your learning style10 modes available
Mental Model
Strings are sequences of characters, but how they are stored and changed depends on the language.
Analogy: Think of strings like a row of boxes holding letters. Some languages let you open and change each box easily, others keep the boxes locked and give you a new row when you want to change something.
String: [H] -> [e] -> [l] -> [l] -> [o] -> null
↑ head pointer to first character
Dry Run Walkthrough
Input: string: 'Hello', change character at index 1 to 'a'
Goal: Show how changing a character works differently in mutable vs immutable strings
Step 1: Try to change character at index 1 from 'e' to 'a' in a mutable string
[H] -> [a] -> [l] -> [l] -> [o] -> null
Why: In mutable strings, we can directly change the character in place
Step 2: Try to change character at index 1 from 'e' to 'a' in an immutable string
Original string: [H] -> [e] -> [l] -> [l] -> [o] -> null
New string: [H] -> [a] -> [l] -> [l] -> [o] -> null
Why: Immutable strings cannot be changed directly, so a new string is created with the change
Step 3: Use the new string for further operations
New string: [H] -> [a] -> [l] -> [l] -> [o] -> null
Why: Operations continue on the new string since the original is unchanged
Result:
Mutable string after change: H -> a -> l -> l -> o -> null
Immutable string original: H -> e -> l -> l -> o -> null
Immutable string new: H -> a -> l -> l -> o -> null
Annotated Code
DSA Typescript
class MutableString {
  chars: string[];
  constructor(s: string) {
    this.chars = s.split('');
  }
  changeChar(index: number, c: string) {
    if (index >= 0 && index < this.chars.length) {
      this.chars[index] = c; // directly change character
    }
  }
  toString() {
    return this.chars.join('');
  }
}

function changeCharImmutable(s: string, index: number, c: string): string {
  if (index < 0 || index >= s.length) return s;
  // create new string with changed character
  return s.slice(0, index) + c + s.slice(index + 1);
}

// Driver code
const mutableStr = new MutableString('Hello');
mutableStr.changeChar(1, 'a');
console.log('Mutable string after change:', mutableStr.toString());

const immutableStr = 'Hello';
const newImmutableStr = changeCharImmutable(immutableStr, 1, 'a');
console.log('Immutable string original:', immutableStr);
console.log('Immutable string new:', newImmutableStr);
this.chars[index] = c; // directly change character
directly update character in mutable string array
return s.slice(0, index) + c + s.slice(index + 1);
create new string with changed character for immutable string
OutputSuccess
Mutable string after change: Hallo Immutable string original: Hello Immutable string new: Hallo
Complexity Analysis
Time: O(n) because creating a new string requires copying characters except one
Space: O(n) for immutable strings since a new string is created; O(n) for mutable strings due to array storage
vs Alternative: Mutable strings allow in-place changes with less memory, immutable strings require new copies but offer safety and simplicity
Edge Cases
index out of bounds (negative or >= string length)
No change occurs; original string remains the same
DSA Typescript
if (index < 0 || index >= s.length) return s;
empty string input
No change occurs; empty string remains empty
DSA Typescript
if (index < 0 || index >= s.length) return s;
When to Use This Pattern
When you need to change characters in strings, check if the language uses mutable or immutable strings to decide if you can change in place or must create a new string.
Common Mistakes
Mistake: Trying to change a character directly in an immutable string variable
Fix: Create a new string with the desired changes instead of modifying the original
Summary
Strings can be mutable or immutable depending on the language, affecting how changes are made.
Use mutable strings when you want to change characters directly; use immutable strings when safety and simplicity are priorities.
The key insight is that immutable strings require creating new copies for changes, while mutable strings allow direct updates.

Practice

(1/5)
1. In TypeScript, what is the type of a string when you use single quotes like 'hello' compared to double quotes like "hello"?
easy
A. Both are of type string and behave the same
B. Single quotes create a character, double quotes create a string
C. Single quotes create a string, double quotes create a character
D. Single quotes are invalid syntax in TypeScript

Solution

  1. Step 1: Understand string literals in TypeScript

    TypeScript treats both single and double quotes as string delimiters, so both create string values.
  2. Step 2: Confirm no character type in TypeScript

    Unlike some languages, TypeScript does not have a separate character type; single quotes do not create characters.
  3. Final Answer:

    Both are of type string and behave the same -> Option A
  4. Quick Check:

    Single and double quotes create strings = A [OK]
Hint: Single and double quotes both create strings in TypeScript [OK]
Common Mistakes:
  • Thinking single quotes create characters
  • Confusing TypeScript with languages like C
  • Assuming single quotes are invalid
2. Which of the following is the correct way to declare a multi-line string in TypeScript?
easy
A. Using double quotes with + operator: const s = "line1" + "line2";
B. Using single quotes with \n: const s = 'line1\nline2';
C. Using backticks: const s = `line1\nline2`;
D. Using triple quotes: const s = '''line1\nline2''';

Solution

  1. Step 1: Identify multi-line string syntax in TypeScript

    TypeScript supports template literals using backticks (`) which allow multi-line strings directly.
  2. Step 2: Check other options for correctness

    Single and double quotes require explicit \n for new lines; triple quotes are invalid in TypeScript.
  3. Final Answer:

    Using backticks: const s = `line1\nline2`; -> Option C
  4. Quick Check:

    Backticks allow multi-line strings = A [OK]
Hint: Use backticks for multi-line strings in TypeScript [OK]
Common Mistakes:
  • Using triple quotes like Python
  • Expecting single or double quotes to support multi-line directly
  • Forgetting to escape newlines in single/double quotes
3. What will be the output of the following TypeScript code?
const s = `Hello\nWorld`;
console.log(s.length);
medium
A. Error
B. 12
C. 10
D. 11

Solution

  1. Step 1: Understand the string content

    The string is a template literal with an actual newline character between Hello and World, not the two-character escape sequence.
  2. Step 2: Count characters including the newline

    Characters: H(1) e(2) l(3) l(4) o(5) \n is a single newline character (counts as 1), W(6) o(7) r(8) l(9) d(10). So length is 11.
  3. Final Answer:

    11 -> Option D
  4. Quick Check:

    Template literals interpret \n as newline character = A [OK]
Hint: Template literals interpret \n as a single newline character [OK]
Common Mistakes:
  • Assuming \n is two characters in length
  • Counting only visible characters
  • Expecting runtime error due to escape
4. Identify the error in this TypeScript code snippet:
const greeting = 'Hello;
console.log(greeting);
medium
A. Missing closing single quote for the string
B. Incorrect use of backticks instead of single quotes
C. Missing semicolon after console.log statement
D. No error, code runs fine

Solution

  1. Step 1: Check string syntax

    The string starts with a single quote but does not have a closing single quote before the newline.
  2. Step 2: Understand string literal rules

    Single-quoted strings cannot span multiple lines without escape; missing closing quote causes syntax error.
  3. Final Answer:

    Missing closing single quote for the string -> Option A
  4. Quick Check:

    Unclosed string literal = D [OK]
Hint: Strings must be closed before newline unless using backticks [OK]
Common Mistakes:
  • Thinking backticks are required here
  • Ignoring missing quote errors
  • Assuming semicolon omission causes error
5. Given the following TypeScript code, what will be the output?
const s1 = 'café';
const s2 = 'cafe\u0301';
console.log(s1 === s2);

Note: \u0301 is a Unicode combining acute accent.
hard
A. true
B. false
C. SyntaxError
D. RuntimeError

Solution

  1. Step 1: Understand Unicode normalization in strings

    s1 uses a single character 'é' (U+00E9), while s2 uses 'e' plus combining accent (U+0301).
  2. Step 2: Compare strings with different Unicode forms

    Direct equality compares code units; different Unicode sequences mean s1 !== s2.
  3. Final Answer:

    false -> Option B
  4. Quick Check:

    Unicode composed vs decomposed forms differ = C [OK]
Hint: Unicode composed and decomposed strings are not equal by default [OK]
Common Mistakes:
  • Assuming visually same means equal
  • Ignoring Unicode combining characters
  • Expecting automatic normalization in equality
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard