# Suffix Trie Construction

![](/files/x08ZnK2H1OvcWKacR3oY)

* recursive

```tsx
// Do not edit the class below except for the
// populateSuffixTrieFrom and contains methods.
// Feel free to add new properties and methods
// to the class.
class SuffixTrie {
  constructor(string) {
    this.root = {};
    this.endSymbol = '*';
    this.populateSuffixTrieFrom(string);
  }

  // O(n^2) time | O(n^2) space: n is the length of string
  populateSuffixTrieFrom(string, idx = 0) {
    if (idx >= string.length) {
      return this.root;
    }

    let node = this.root;
    for (let i = idx; i < string.length; i++) {
      const c = string[i];
      if (node[c] === undefined) node[c] = {};
      node = node[c];
    }
    node[this.endSymbol] = true;
    
    return this.populateSuffixTrieFrom(string, idx + 1);
  }

  // O(w) time | O(1) space: w is the length of string
  contains(string) {
    let node = this.root;
    for (const c of string) {
      if (node[c] === undefined) return false;
      node = node[c];
    }
    return node[this.endSymbol] === true;
  }

}

// Do not edit the line below.
exports.SuffixTrie = SuffixTrie
```

* iteration

```tsx
  // O(n^2) time | O(n^2) space: n is the length of string
  populateSuffixTrieFrom(string) {

    for (let i = 0; i < string.length; i++) {
	    let node = this.root;
			for (let j = i; j < string.length; j++) {
	      const c = string[j];
	      if (node[c] === undefined) node[c] = {};
	      node = node[c];
			}
	    node[this.endSymbol] = true;
    }
  
    return this.root;
  }
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://algorithm.prettylog.com/algorithm-problems/algoexpert/medium/suffix-trie-construction.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
