Why My Code Works Locally But Fails on Submission — Common Reasons

"Works on my machine" is one of the most frustrating programming situations. Your code passes local tests but fails on the judge, server, or CI. The root cause is almost always an environment difference: input format, file paths, time limits, or assumptions that only hold locally. This guide covers every category with working fixes.

Input format

judge input is different from your local test

Time limit

O(n²) works for small input, TLE on large judge input

Edge cases

empty input, single element, max values not tested

Platform diff

OS, language version, integer size differences

1

Competitive Programming Submission Failures

Quick fact

Most "works locally, fails on judge" errors fall into 5 categories: (1) Wrong input reading method, (2) Time Limit Exceeded with large inputs, (3) Edge cases not tested locally, (4) Integer overflow, (5) Uninitialized variables that happen to be zero locally.

TLE — Time Limit Exceeded

Your O(n²) solution works for your 100-element test but TLEs on the judge's 100,000-element input. Fix: analyze time complexity, switch to O(n log n) or O(n) algorithm. A 10^8 operation limit per second is the standard estimate.

Wrong input format

You're reading a single line but judge sends multiple test cases. Or reading with cin but judge uses whitespace differently. Always read exactly what the problem statement describes — no assumptions.

Integer overflow

int maxes at ~2.1 billion. If n = 10^5 and you compute n*n = 10^10, that overflows int silently. Use long long in C++, long in Java, BigInteger if needed. Overflow produces wrong answers, not runtime errors — making it hard to detect.

Uninitialized variables

int count; // undefined value (might be 0 locally by luck). Always initialize: int count = 0;. Many local environments zero-initialize; judges and online platforms do not. This is one of the most common subtle bugs.

2

Reading Input Correctly for Competitive Programming

One of the most common causes of local pass / judge fail is reading input incorrectly. The judge sends exactly what the problem specifies — your local test might not. Use bulk input reading for speed and correctness on large inputs.

pythonCompetitive programming — correct input reading template
# Always test edge cases before submitting
def solve(n, arr):
    # Your solution here
    pass

# Read exactly as judge sends — bulk read is fastest
import sys

def main():
    input_data = sys.stdin.read().split()
    idx = 0

    t = int(input_data[idx]); idx += 1  # number of test cases
    for _ in range(t):
        n = int(input_data[idx]); idx += 1
        arr = [int(input_data[idx+i]) for i in range(n)]
        idx += n
        print(solve(n, arr))

# Edge case tests — always run these before submitting
print("=== Edge cases ===")
print(solve(1, [0]))           # single element zero
print(solve(1, [10**9]))       # max value
print(solve(0, []))            # empty input
print(solve(5, [1,1,1,1,1]))   # all same
print(solve(5, [-1,-2,-3,-4,-5]))  # all negative

main()  # comment out for submission
cppC++ — fast I/O and integer overflow prevention
#include <bits/stdc++.h>
using namespace std;

// Fast I/O — required for large inputs
ios_base::sync_with_stdio(false);
cin.tie(NULL);

// Use long long to prevent overflow
long long n, m;
cin >> n >> m;

// Dangerous: n*n might overflow if n is large
// long long result = n * n;  // ❌ if n is int

// Safe: explicitly cast to long long before multiply
long long result = (long long)n * n;  // ✅

// Or declare n as long long from the start
long long a, b;
cin >> a >> b;
long long product = a * b;  // safe — both long long
3

Production Deployment Failures

Environment variables missing

process.env.API_KEY works locally (.env file). Fails in production because .env isn't deployed. Fix: add to deployment env vars / secrets manager. Never commit .env files to git.

File path differences

Local: __dirname + "/data.json" works. Server: different directory structure. Fix: use path.join(__dirname, "data.json") for relative paths, or move to config-driven paths.

Node/Python version mismatch

Local: Node 20. Server: Node 16. Optional chaining (?.) doesn't exist in old Node. Fix: specify engine version in package.json, use .nvmrc, Docker for exact env match.

Case-sensitive file system

Mac/Windows: import "./Component" works even if file is "component.tsx". Linux server: case-sensitive — import must exactly match. Fix: always match case exactly in imports.

4

CI/CD Pipeline Failures

CI failures that don't reproduce locally

The most common CI-only failures: missing environment variables in CI config, different Node.js version in CI runner, test isolation issues (tests pass in random order locally, fail in fixed order on CI), and missing native dependencies for npm packages with native bindings.
yamlGitHub Actions — match local environment precisely
name: CI
on: [push, pull_request]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      # Pin exact Node version — match your local version
      - uses: actions/setup-node@v4
        with:
          node-version: '20.11.0'  # exact version, not just '20'
          cache: 'npm'

      # Verify env vars are present
      - name: Check required env vars
        run: |
          test -n "$DATABASE_URL" || (echo "Missing DATABASE_URL" && exit 1)
          test -n "$API_KEY" || (echo "Missing API_KEY" && exit 1)
        env:
          DATABASE_URL: ${{ secrets.DATABASE_URL }}
          API_KEY: ${{ secrets.API_KEY }}

      - run: npm ci
      - run: npm test
5

Debug Checklist — Production Deployments

javascriptStartup checks — catch environment issues immediately
// Run these checks at app startup — fail fast with clear errors
const required = ['DATABASE_URL', 'API_KEY', 'SECRET_KEY'];
const missing = required.filter(k => !process.env[k]);
if (missing.length > 0) {
  throw new Error('Missing required env vars: ' + missing.join(', '));
}

// Use path.join for cross-platform file paths
const path = require('path');
const dataPath = path.join(__dirname, '..', 'data', 'config.json');
// Not: '../data/config.json' (works on Mac, may fail on Windows CI)

// Log runtime environment to catch version mismatches
console.log('Node version:', process.version);
console.log('Platform:', process.platform);
console.log('Environment:', process.env.NODE_ENV);

// Always use exact case in imports (for Linux servers)
// ✅ import Button from './Button'    (file is Button.tsx)
// ❌ import Button from './button'    (file is Button.tsx — fails on Linux)
6

Docker — The Nuclear Option for Environment Differences

Docker eliminates environment differences completely

Use Docker for production deployments to ensure dev and prod use identical environments. A Dockerfile pins OS, runtime version, and system libraries. What runs in your Docker container locally runs identically in production — eliminating 90% of "works locally" issues for deployment scenarios.
dockerfileDockerfile — pin exact versions for reproducibility
# Use exact version tag, never :latest
FROM node:20.11.0-alpine3.19

WORKDIR /app

# Copy package files first (for layer caching)
COPY package*.json ./
RUN npm ci --only=production

COPY . .

# Build step
RUN npm run build

# Run as non-root user for security
USER node

EXPOSE 3000
CMD ["node", "server.js"]
7

Stress Testing Before Submission

1

Identify time complexity

Count nested loops. O(n²) with n=10^5 = 10^10 operations = TLE. O(n log n) = safe.

2

Generate max-size input

n = problem maximum (e.g., 10^5). Use random values including edge cases (0, negatives, max values).

3

Run with timing

time python solution.py < large_input.txt. If >1-2 seconds, you will TLE.

4

Stress test against brute force

Run optimized + brute force on small random inputs. Compare output. Finds WA bugs before submission.

5

Test boundary conditions

n=1, n=max, all same values, sorted ascending/descending, empty arrays if applicable.

Frequently Asked Questions

Related Programming & Development Guides

Continue with closely related troubleshooting guides and developer workflows.