> ## Documentation Index
> Fetch the complete documentation index at: https://docs.hopx.ai/llms.txt
> Use this file to discover all available pages before exploring further.

# Coding Interview Platform

> Build a technical interview platform with problem execution environments, time limit enforcement, test case management, and performance monitoring

Build a production-ready coding interview platform where candidates solve problems under time constraints. This cookbook demonstrates how to create a platform similar to LeetCode or HackerRank for technical interviews.

## Overview

Coding interview platforms provide a controlled environment for technical assessments. Candidates solve problems within time limits, and the system validates solutions, monitors performance, and generates assessment reports.

## Prerequisites

* HopX API key ([Get one here](https://console.hopx.dev/api-keys))
* Python 3.8+ or Node.js 16+
* Understanding of interview assessment workflows
* Basic knowledge of performance monitoring

## Architecture

```
┌──────────────┐
│  Candidate   │ Submits solution
└──────┬───────┘
       │
       ▼
┌─────────────────┐
│  Interview      │ Validate, monitor
│   Platform      │
└──────┬──────────┘
       │
       ▼
┌─────────────────┐
│  HopX Sandbox   │ Execute & time
└─────────────────┘
```

## Implementation

### Step 1: Time-Limited Execution

Execute code with strict time limits:

<CodeGroup>
  ```python Python theme={null}
  from hopx_ai import Sandbox
  import os
  import time
  from typing import Dict, Any

  class InterviewPlatform:
      def __init__(self, api_key: str):
          self.api_key = api_key
      
      def execute_with_time_limit(self, code: str, time_limit: int, language: str = "python") -> Dict[str, Any]:
          """Execute code with strict time limit"""
          sandbox = None
          start_time = time.time()
          
          try:
              sandbox = Sandbox.create(
                  template="code-interpreter",
                  api_key=self.api_key,
                  timeout_seconds=time_limit + 5
              )
              
              # Execute with timeout
              result = sandbox.run_code(code, language=language, timeout=time_limit)
              
              elapsed = time.time() - start_time
              
              # Check if timeout was exceeded
              if elapsed >= time_limit:
                  return {
                      "success": False,
                      "timeout": True,
                      "elapsed_time": elapsed,
                      "time_limit": time_limit,
                      "error": "Time limit exceeded"
                  }
              
              return {
                  "success": result.success,
                  "stdout": result.stdout,
                  "stderr": result.stderr,
                  "elapsed_time": elapsed,
                  "time_limit": time_limit,
                  "within_limit": elapsed < time_limit
              }
          except Exception as e:
              return {
                  "success": False,
                  "error": str(e),
                  "elapsed_time": time.time() - start_time
              }
          finally:
              if sandbox:
                  sandbox.kill()

  # Usage
  platform = InterviewPlatform(api_key=os.getenv("HOPX_API_KEY"))

  result = platform.execute_with_time_limit(
      code="print('Hello')",
      time_limit=5  # 5 second limit
  )
  print(result)
  ```

  ```javascript JavaScript theme={null}
  import { Sandbox } from '@hopx-ai/sdk';

  class InterviewPlatform {
      constructor(apiKey) {
          this.apiKey = apiKey;
      }
      
      async executeWithTimeLimit(code, timeLimit, language = 'python') {
          let sandbox = null;
          const startTime = Date.now();
          
          try {
              sandbox = await Sandbox.create({
                  template: 'code-interpreter',
                  apiKey: this.apiKey,
                  timeoutSeconds: timeLimit + 5
              });
              
              // Execute with timeout
              const result = await sandbox.runCode(code, {
                  language,
                  timeout: timeLimit
              });
              
              const elapsed = (Date.now() - startTime) / 1000;
              
              // Check if timeout was exceeded
              if (elapsed >= timeLimit) {
                  return {
                      success: false,
                      timeout: true,
                      elapsedTime: elapsed,
                      timeLimit,
                      error: 'Time limit exceeded'
                  };
              }
              
              return {
                  success: result.success,
                  stdout: result.stdout,
                  stderr: result.stderr,
                  elapsedTime: elapsed,
                  timeLimit,
                  withinLimit: elapsed < timeLimit
              };
          } catch (error) {
              return {
                  success: false,
                  error: error.message,
                  elapsedTime: (Date.now() - startTime) / 1000
              };
          } finally {
              if (sandbox) {
                  await sandbox.kill();
              }
          }
      }
  }

  // Usage
  const platform = new InterviewPlatform(process.env.HOPX_API_KEY);

  const result = await platform.executeWithTimeLimit(
      "print('Hello')",
      5  // 5 second limit
  );
  console.log(result);
  ```
</CodeGroup>

### Step 2: Performance Monitoring

Monitor code performance:

<CodeGroup>
  ```python Python theme={null}
  class PerformanceMonitor:
      def __init__(self, sandbox: Sandbox):
          self.sandbox = sandbox
      
      def monitor_execution(self, code: str) -> Dict[str, Any]:
          """Monitor code execution performance"""
          import time
          
          start_time = time.time()
          result = self.sandbox.run_code(code, timeout=30)
          elapsed = time.time() - start_time
          
          # Get system metrics
          metrics = self.sandbox.get_metrics_snapshot()
          
          return {
              "execution_time": elapsed,
              "code_execution_time": result.execution_time,
              "memory_usage": getattr(metrics, 'memory_usage_mb', 0) if hasattr(metrics, 'memory_usage_mb') else 0,
              "cpu_usage": getattr(metrics, 'cpu_percent', 0) if hasattr(metrics, 'cpu_percent') else 0,
              "success": result.success
          }

  # Usage
  sandbox = Sandbox.create(template="code-interpreter", api_key=os.getenv("HOPX_API_KEY"))
  monitor = PerformanceMonitor(sandbox)

  metrics = monitor.monitor_execution("print('Hello')")
  print(f"Execution time: {metrics['execution_time']:.2f}s")
  print(f"Memory usage: {metrics['memory_usage']}MB")

  sandbox.kill()
  ```

  ```javascript JavaScript theme={null}
  class PerformanceMonitor {
      constructor(sandbox) {
          this.sandbox = sandbox;
      }
      
      async monitorExecution(code) {
          const startTime = Date.now();
          const result = await this.sandbox.runCode(code, { timeout: 30 });
          const elapsed = (Date.now() - startTime) / 1000;
          
          // Get system metrics
          const metrics = await this.sandbox.getSystemMetrics();
          
          return {
              executionTime: elapsed,
              codeExecutionTime: result.execution_time,
              memoryUsage: metrics.memory_usage_mb || 0,
              cpuUsage: metrics.cpu_percent || 0,
              success: result.success
          };
      }
  }

  // Usage
  const sandbox = await Sandbox.create({
      template: 'code-interpreter',
      apiKey: process.env.HOPX_API_KEY
  });
  const monitor = new PerformanceMonitor(sandbox);

  const metrics = await monitor.monitorExecution("print('Hello')");
  console.log(`Execution time: ${metrics.executionTime.toFixed(2)}s`);
  console.log(`Memory usage: ${metrics.memoryUsage}MB`);

  await sandbox.kill();
  ```
</CodeGroup>

## Best Practices

1. **Time Enforcement**: Strictly enforce time limits
2. **Performance Tracking**: Monitor execution time and resource usage
3. **Test Case Management**: Organize test cases efficiently
4. **Result Reporting**: Generate comprehensive assessment reports

## Related Cookbooks

* [Online Coding Platform](/cookbooks/educational/online-coding-platform) - Full coding platform
* [Interactive Tutorials](/cookbooks/educational/interactive-tutorials) - Learning platform
* [Isolated Test Execution](/cookbooks/testing/isolated-test-execution) - Test isolation

## Next Steps

1. Implement problem database
2. Add candidate authentication
3. Create assessment dashboard
4. Implement result analytics
5. Add video/audio interview features
