Spaces:
Running
Running
File size: 9,886 Bytes
8800c81 59a8d26 8800c81 53d8367 8800c81 53d8367 8800c81 53d8367 8800c81 59a8d26 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 | import React from 'react';
import type { ProblemItem, ParsedExample, ProblemSolution } from '../types/reviewTypes';
export function parseProblemContent(problem: ProblemItem | null | undefined): {
description: string;
examples: ParsedExample[];
constraints: string[];
} {
if (!problem) return { description: '', examples: [], constraints: [] };
let description = problem.description || '';
let examples: ParsedExample[] = [];
let constraints: string[] = [];
// 1. If problem already has structured examples
if (Array.isArray(problem.examples) && problem.examples.length > 0) {
examples = problem.examples.map((ex) => {
if (typeof ex === 'string') {
return { input: ex, output: '' };
}
return {
input: ex?.input || '',
output: ex?.output || '',
explanation: ex?.explanation || ''
};
});
}
// 2. If problem already has structured constraints
if (Array.isArray(problem.constraints) && problem.constraints.length > 0) {
constraints = problem.constraints.map((c) => String(c).replace(/^[\u2022\-*]\s*/, '').trim()).filter(Boolean);
} else if (typeof problem.constraints === 'string' && problem.constraints.trim()) {
constraints = problem.constraints.split('\n').map((c) => c.replace(/^[\u2022\-*]\s*/, '').trim()).filter(Boolean);
}
// 3. Fallback: Parse raw description if needed
if (examples.length === 0 || constraints.length === 0) {
const exMatch = description.search(/\bExample\s*\d*:/i);
const coMatch = description.search(/\bConstraints\s*:/i);
let firstSplit = -1;
if (exMatch !== -1 && coMatch !== -1) {
firstSplit = Math.min(exMatch, coMatch);
} else if (exMatch !== -1) {
firstSplit = exMatch;
} else if (coMatch !== -1) {
firstSplit = coMatch;
}
if (firstSplit !== -1) {
const cleanDesc = description.substring(0, firstSplit).trim();
const bodyRest = description.substring(firstSplit);
let exPart = bodyRest;
let coPart = '';
const coInRest = bodyRest.search(/\bConstraints\s*:/i);
if (coInRest !== -1) {
exPart = bodyRest.substring(0, coInRest).trim();
coPart = bodyRest.substring(coInRest).replace(/\bConstraints\s*:/i, '').trim();
}
if (examples.length === 0 && exPart) {
const regex = /\bExample\s*(\d*)\s*:/gi;
const matches: { index: number; text: string }[] = [];
let m;
while ((m = regex.exec(exPart)) !== null) {
matches.push({ index: m.index, text: m[0] });
}
for (let i = 0; i < matches.length; i++) {
const start = matches[i].index + matches[i].text.length;
const end = i + 1 < matches.length ? matches[i + 1].index : exPart.length;
const block = exPart.substring(start, end).trim();
const inpMatch = block.match(/Input:\s*([\s\S]+?)(?=(?:Output:|Explanation:|$))/i);
const outMatch = block.match(/Output:\s*([\s\S]+?)(?=(?:Explanation:|$))/i);
const expMatch = block.match(/Explanation:\s*([\s\S]+)/i);
const inp = inpMatch ? inpMatch[1].trim() : '';
const out = outMatch ? outMatch[1].trim() : '';
const exp = expMatch ? expMatch[1].trim() : '';
if (inp || out) {
examples.push({ input: inp, output: out, explanation: exp });
} else if (block) {
examples.push({ input: block, output: '', explanation: '' });
}
}
}
if (constraints.length === 0 && coPart) {
constraints = coPart
.split('\n')
.map((l) => l.replace(/^[\u2022\-*]\s*/, '').trim())
.filter(Boolean);
}
if (examples.length > 0 || constraints.length > 0) {
description = cleanDesc;
}
}
}
return { description, examples, constraints };
}
import { renderInlineMarkdown } from './markdownUtils';
import { MarkdownRenderer } from '../components/MarkdownRenderer';
export { renderInlineMarkdown };
export function parseMarkdown(text: string): React.ReactNode[] {
if (!text) return [];
return [<MarkdownRenderer key="md-content" content={text} />];
}
export interface ParsedProblemTitle {
cleanTitle: string;
approachVariant: string | null;
pattern: string;
}
/**
* Normalizes problem title, extracts approach variants (e.g. "Hash Map (One-Pass)"),
* and resolves the canonical algorithm pattern, preventing repetitive "Method 1" echoes.
*/
export function parseProblemTitle(
rawName: string | undefined | null,
catalogName?: string | null,
rawPattern?: string | null,
catalogPattern?: string | null
): ParsedProblemTitle {
const isGeneric = (str?: string | null) =>
!str || /^Method\s*\d*$/i.test(str.trim()) || str.trim().toLowerCase() === 'standard';
let name = (rawName || catalogName || 'Algorithm Problem').trim();
let approachVariant: string | null = null;
// 1. If catalogName is provided and name starts with catalogName, extract the suffix
if (catalogName && name.toLowerCase().startsWith(catalogName.toLowerCase())) {
const suffix = name.slice(catalogName.length).trim();
name = catalogName; // Canonical clean title
if (suffix) {
// Check for:
// " - Method 1 (Hash Map (One-Pass))"
// " - Method 1 (Method 1)"
const methodWithParenMatch = suffix.match(/^[-\s]*Method\s*(\d+)\s*\((.+)\)$/i);
if (methodWithParenMatch) {
const methodNum = parseInt(methodWithParenMatch[1], 10);
const parenContent = methodWithParenMatch[2].trim();
if (!isGeneric(parenContent)) {
approachVariant = parenContent;
} else if (methodNum > 1) {
approachVariant = `Method ${methodNum}`;
}
} else {
const methodOnlyMatch = suffix.match(/^[-\s]*Method\s*(\d+)/i);
if (methodOnlyMatch) {
const methodNum = parseInt(methodOnlyMatch[1], 10);
if (methodNum > 1) {
approachVariant = `Method ${methodNum}`;
}
} else {
const parenMatch = suffix.match(/^[-\s]*\((.+)\)$/);
if (parenMatch) {
const parenContent = parenMatch[1].trim();
if (!isGeneric(parenContent)) {
approachVariant = parenContent;
}
} else {
const hyphenMatch = suffix.match(/^[-\s]+([^-]+)$/);
if (hyphenMatch && !isGeneric(hyphenMatch[1])) {
approachVariant = hyphenMatch[1].trim();
}
}
}
}
}
} else {
// 2. Fallback when catalogName is not available or doesn't match prefix
const methodParenRegex = /^(.*?)\s*-\s*Method\s*(\d+)\s*\((.+)\)$/i;
const methodParenMatch = name.match(methodParenRegex);
if (methodParenMatch) {
name = methodParenMatch[1].trim();
const methodNum = parseInt(methodParenMatch[2], 10);
const parenContent = methodParenMatch[3].trim();
if (!isGeneric(parenContent)) {
approachVariant = parenContent;
} else if (methodNum > 1) {
approachVariant = `Method ${methodNum}`;
}
} else {
const methodRegex = /^(.*?)\s*-\s*Method\s*(\d+)$/i;
const methodMatch = name.match(methodRegex);
if (methodMatch) {
name = methodMatch[1].trim();
const methodNum = parseInt(methodMatch[2], 10);
if (methodNum > 1) {
approachVariant = `Method ${methodNum}`;
}
} else {
const parenMethodRegex = /^(.*?)\s*\(\s*Method\s*(\d+)\s*\)$/i;
const parenMethodMatch = name.match(parenMethodRegex);
if (parenMethodMatch) {
name = parenMethodMatch[1].trim();
const methodNum = parseInt(parenMethodMatch[2], 10);
if (methodNum > 1) {
approachVariant = `Method ${methodNum}`;
}
}
}
}
}
// Determine resolved pattern:
let resolvedPattern = 'General Algorithm';
if (!isGeneric(rawPattern)) {
resolvedPattern = rawPattern!.trim();
} else if (!isGeneric(catalogPattern)) {
resolvedPattern = catalogPattern!.trim();
} else if (approachVariant && !isGeneric(approachVariant)) {
resolvedPattern = approachVariant;
}
return {
cleanTitle: name,
approachVariant,
pattern: resolvedPattern
};
}
/**
* Normalizes problem solutions into a clean ProblemSolution[] array.
* If the problem has a dedicated solutions array, it uses it.
* Otherwise, it creates fallback solutions from reference_code, pattern, optimal_time, optimal_space, and userSolution.
*/
export function normalizeProblemSolutions(
problem: ProblemItem | null | undefined,
officialSolution?: string,
userSolution?: string
): ProblemSolution[] {
if (!problem) return [];
if (Array.isArray(problem.solutions) && problem.solutions.length > 0) {
return problem.solutions;
}
const results: ProblemSolution[] = [];
const primaryCode = officialSolution || problem.reference_code || '';
const pattern = problem.pattern || 'General Algorithm';
const timeComplexity = problem.optimal_time || 'O(N)';
const spaceComplexity = problem.optimal_space || 'O(1)';
if (primaryCode || pattern) {
results.push({
id: 'sol-1',
name: problem.approach_variant || 'Optimal Solution',
pattern,
time_complexity: timeComplexity,
space_complexity: spaceComplexity,
code: primaryCode,
explanation: problem.how_to_solve || '',
is_optimal: true
});
}
// If user has a distinct personal solution not matching official, add as Solution 2
if (userSolution && userSolution.trim() && userSolution.trim() !== primaryCode.trim()) {
results.push({
id: 'sol-2',
name: 'Personal Solution',
pattern,
time_complexity: timeComplexity,
space_complexity: spaceComplexity,
code: userSolution,
is_optimal: false
});
}
return results;
}
|