You are given a string s that contains some bracket pairs, with each pair containing a non-empty key.
For example, in the string "(name)is(age)yearsold", there are two bracket pairs that contain the keys "name" and "age".
You know the values of a wide range of keys. This is represented by a 2D string array knowledge where each knowledge[i] = [keyi, valuei] indicates that key keyi has a value of valuei.
You are tasked to evaluate all of the bracket pairs. When you evaluate a bracket pair that contains some key keyi, you will:
Replace keyi and the bracket pair with the key's corresponding valuei.
If you do not know the value of the key, you will replace keyi and the bracket pair with a question mark "?".
Each key will appear at most once in your knowledge. There will not be any nested brackets in s.
Return the resulting string after evaluating all of the bracket pairs.
The key insight is to use a hash map to convert O(k) linear searches into O(1) lookups. Build the hash map once from the knowledge array, then scan the string to find bracket pairs and replace them instantly. Best approach is hash map optimization with Time: O(n+k), Space: O(k).
Common Approaches
✓
Dfs
⏱️ Time: N/A
Space: N/A
Brute Force Linear Search
⏱️ Time: O(n×k)
Space: O(1)
Scan the string to find bracket pairs, extract keys, then search through the knowledge array linearly to find matching values. Replace each bracket pair with its corresponding value or '?' if not found.
Hash Map Optimization
⏱️ Time: O(n+k)
Space: O(k)
First pass builds a hash map from the knowledge array for O(1) key lookups. Second pass scans the string once, extracting keys from bracket pairs and looking them up instantly in the hash map.
Algorithm Steps — Algorithm Steps
Code -
solution.c — C
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char* evaluate(char* s, char** keys, char** values, int knowledgeSize) {
int len = strlen(s);
char* result = (char*)malloc(10000 * sizeof(char));
int resultIdx = 0;
for (int i = 0; i < len; i++) {
if (s[i] == '(') {
// Find the closing bracket
int j = i + 1;
while (j < len && s[j] != ')') {
j++;
}
if (j < len) { // Found closing bracket
// Extract the key
int keyLen = j - i - 1;
char* key = (char*)malloc((keyLen + 1) * sizeof(char));
strncpy(key, s + i + 1, keyLen);
key[keyLen] = '\0';
// Look up the key in knowledge
int found = 0;
for (int k = 0; k < knowledgeSize; k++) {
if (strcmp(key, keys[k]) == 0) {
// Found the key, append its value
strcpy(result + resultIdx, values[k]);
resultIdx += strlen(values[k]);
found = 1;
break;
}
}
if (!found) {
// Key not found, append '?'
result[resultIdx++] = '?';
}
free(key);
i = j; // Skip to after the closing bracket
}
} else {
// Regular character, just append
result[resultIdx++] = s[i];
}
}
result[resultIdx] = '\0';
return result;
}
void parseKnowledge(char* knowledgeStr, char*** keys, char*** values, int* size) {
*keys = (char**)malloc(100 * sizeof(char*));
*values = (char**)malloc(100 * sizeof(char*));
*size = 0;
int len = strlen(knowledgeStr);
int i = 0;
// Skip initial '['
while (i < len && knowledgeStr[i] != '[') i++;
i++;
while (i < len) {
// Skip whitespace and commas
while (i < len && (knowledgeStr[i] == ' ' || knowledgeStr[i] == ',' || knowledgeStr[i] == '\n')) i++;
if (i >= len || knowledgeStr[i] == ']') break;
// Expect '['
if (knowledgeStr[i] != '[') break;
i++;
// Skip whitespace
while (i < len && knowledgeStr[i] == ' ') i++;
// Expect '"' for key
if (i >= len || knowledgeStr[i] != '"') break;
i++;
// Read key
int keyStart = i;
while (i < len && knowledgeStr[i] != '"') i++;
int keyLen = i - keyStart;
(*keys)[*size] = (char*)malloc((keyLen + 1) * sizeof(char));
strncpy((*keys)[*size], knowledgeStr + keyStart, keyLen);
(*keys)[*size][keyLen] = '\0';
// Skip '"' and comma
i++;
while (i < len && (knowledgeStr[i] == ' ' || knowledgeStr[i] == ',')) i++;
// Expect '"' for value
if (i >= len || knowledgeStr[i] != '"') break;
i++;
// Read value
int valueStart = i;
while (i < len && knowledgeStr[i] != '"') i++;
int valueLen = i - valueStart;
(*values)[*size] = (char*)malloc((valueLen + 1) * sizeof(char));
strncpy((*values)[*size], knowledgeStr + valueStart, valueLen);
(*values)[*size][valueLen] = '\0';
// Skip '"' and ']'
i++;
while (i < len && knowledgeStr[i] != ']') i++;
i++;
(*size)++;
}
}
int main() {
char s[10000];
char knowledgeStr[100000];
// Read the string
fgets(s, sizeof(s), stdin);
s[strcspn(s, "\n")] = '\0';
// Read the knowledge array
fgets(knowledgeStr, sizeof(knowledgeStr), stdin);
knowledgeStr[strcspn(knowledgeStr, "\n")] = '\0';
char** keys;
char** values;
int knowledgeSize;
parseKnowledge(knowledgeStr, &keys, &values, &knowledgeSize);
char* result = evaluate(s, keys, values, knowledgeSize);
printf("%s\n", result);
// Free memory
for (int i = 0; i < knowledgeSize; i++) {
free(keys[i]);
free(values[i]);
}
free(keys);
free(values);
free(result);
return 0;
}
Time & Space Complexity
Time Complexity
⏱️
n
2n
✓ Linear Growth
Space Complexity
n
2n
✓ Linear Space
28.5K Views
MediumFrequency
~15 minAvg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡Explanation
AI Ready
💡 SuggestionTabto acceptEscto dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen
Algorithm Visualization
Pinch to zoom • Tap outside to close
Test Cases
0 passed
0 failed
3 pending
Select Compiler
Choose a programming language
Compiler list would appear here...
AI Editor Features
Header Buttons
💡
Explain
Get a detailed explanation of your code. Select specific code or analyze the entire file. Understand algorithms, logic flow, and complexity.
🔧
Fix
Automatically detect and fix issues in your code. Finds bugs, syntax errors, and common mistakes. Shows you what was fixed.
💡
Suggest
Get improvement suggestions for your code. Best practices, performance tips, and code quality recommendations.
💬
Ask AI
Open an AI chat assistant to ask any coding questions. Have a conversation about your code, get help with debugging, or learn new concepts.
Smart Actions (Slash Commands)
🔧
/fix Enter
Find and fix issues in your code. Detects common problems and applies automatic fixes.
💡
/explain Enter
Get a detailed explanation of what your code does, including time/space complexity analysis.
🧪
/tests Enter
Automatically generate unit tests for your code. Creates comprehensive test cases.
📝
/docs Enter
Generate documentation for your code. Creates docstrings, JSDoc comments, and type hints.
⚡
/optimize Enter
Get performance optimization suggestions. Improve speed and reduce memory usage.
AI Code Completion (Copilot-style)
👻
Ghost Text Suggestions
As you type, AI suggests code completions shown in gray text. Works with keywords like def, for, if, etc.
Tabto acceptEscto dismiss
💬
Comment-to-Code
Write a comment describing what you want, and AI generates the code. Try: # two sum, # binary search, # fibonacci
💡
Pro Tip: Select specific code before using Explain, Fix, or Smart Actions to analyze only that portion. Otherwise, the entire file will be analyzed.