Java & JavaScript Interview Programs — Problems 11–20
(All Approaches, Detailed)
Each problem includes a precise problem statement, four approaches (Brute • DP–Memo • DP–Tab • Greedy),
Java & JavaScript code, detailed explanations, edge cases, and time/space complexity. Where DP or Greedy are
not applicable, a dedicated note explains why.
11. Matrix Addition & Multiplication
Problem Statement
Given matrices A and B of compatible sizes, compute A + B and A × B. Assume A is n×m and B is m×p for
multiplication.
Approach 1 — Brute Force (Triple-Nested Loops for Multiplication)
Java
public class MatrixOps_Brute {
public static int[][] add(int[][] A,int[][] B){
int n=A.length, m=A[0].length;
int[][] C=new int[n][m];
for (int i=0;i<n;i++)
for (int j=0;j<m;j++)
C[i][j]=A[i][j]+B[i][j];
return C;
}
public static int[][] multiply(int[][] A,int[][] B){
int n=A.length, m=A[0].length, p=B[0].length;
int[][] C=new int[n][p];
for (int i=0;i<n;i++)
for (int k=0;k<m;k++)
for (int j=0;j<p;j++)
C[i][j]+=A[i][k]*B[k][j];
return C;
}
}
JavaScript
function add(A,B){
const n=A.length, m=A[0].length;
const C=Array.from({length:n},()=>Array(m).fill(0));
for (let i=0;i<n;i++) for (let j=0;j<m;j++) C[i][j]=A[i][j]+B[i][j];
return C;
}
function multiply(A,B){
const n=A.length, m=A[0].length, p=B[0].length;
const C=Array.from({length:n},()=>Array(p).fill(0));
for (let i=0;i<n;i++)
for (let k=0;k<m;k++)
for (let j=0;j<p;j++)
C[i][j]+=A[i][k]*B[k][j];
return C;
}
Explanation
Addition is elementwise; multiplication uses the textbook triple loop. Validate dimensions: A is n×m, B is m×p.
Multiplication’s associativity allows loop orders (i-k-j shown) with similar complexity.
Time & Space Complexity
Addition: Time O(nm), Space O(nm) for result. Multiplication: Time O(nmp), Space O(np) for result.
Approach 2/3 — DP–Memo & DP–Tab (Not Applicable Here)
Java
// DP is not needed for fixed matrix multiply; dynamic programming is used for chain order optimization, not a sin
JavaScript
// DP isn't used to compute A×B directly; it is used for optimal parenthesization in Matrix Chain Multiplication (
Explanation
Dynamic programming becomes relevant for **Matrix Chain Multiplication** (choosing the order to multiply many
matrices to minimize scalar ops). For computing a single A×B, DP offers no advantage over the triple loop.
Time & Space Complexity
—
Approach 4 — Greedy (Not Applicable)
Java
// No greedy rule improves a single A×B multiply; standard algorithm is optimal for dense matrices.
JavaScript
// Greedy is meaningful for special cases (sparse blocks/tiling/BLAS heuristics) but not correctness/optimality im
Explanation
Greedy ordering makes sense for a chain of matrices or special hardware layouts. For a single dense multiply,
use standard loops or optimized libraries (BLAS).
Time & Space Complexity
—
12. Count Occurrences Of Each Character
Problem Statement
Given a string s, count the frequency of each character and return a mapping from character to count.
Approach 1 — Brute Force (Rescan For Each Character)
Java
import java.util.*;
public class CharFreq_Brute {
public static Map<Character,Integer> freq(String s){
Map<Character,Integer> res=new LinkedHashMap<>();
for (int i=0;i<s.length();i++){
char c=s.charAt(i);
if (res.containsKey(c)) continue;
int count=0;
for (int j=0;j<s.length();j++) if (s.charAt(j)==c) count++;
res.put(c,count);
}
return res;
}
}
JavaScript
function charFreqBrute(s){
const res=new Map();
for (let i=0;i<s.length;i++){
const c=s[i];
if (res.has(c)) continue;
let cnt=0;
for (let j=0;j<s.length;j++) if (s[j]===c) cnt++;
res.set(c,cnt);
}
return res;
}
Explanation
Count each distinct character by rescanning the entire string; avoids extra memory but quadratic.
Time & Space Complexity
Time O(n^2); Space O(σ) to store frequencies (σ = alphabet size).
Approach 2/3 — DP–Memo & DP–Tab (Not Applicable)
Java
// Counting is a single linear pass; no overlapping subproblems for DP.
JavaScript
// DP does not yield benefit for simple frequency counting.
Explanation
Counting has no optimal substructure/overlap; a single pass with a map is optimal.
Time & Space Complexity
—
Approach 4 — Greedy (Not Applicable)
Java
// Greedy has no role in simple counting.
JavaScript
// Not applicable.
Explanation
Greedy selection doesn’t apply; straightforward counting is best.
Time & Space Complexity
—
Supplement — Optimal Linear Hash Counting
Java
import java.util.*;
public class CharFreq_Optimal {
public static Map<Character,Integer> freq(String s){
Map<Character,Integer> m=new LinkedHashMap<>();
for (char c: s.toCharArray()) m.put(c, m.getOrDefault(c,0)+1);
return m;
}
}
JavaScript
function charFreqOptimal(s){
const m=new Map();
for (const c of s) m.set(c,(m.get(c)||0)+1);
return m;
}
Explanation
Single pass with hashmap preserving insertion order (LinkedHashMap/Map).
Time & Space Complexity
Time O(n); Space O(σ).
13. Largest Number < N Without Digit d
Problem Statement
Given an integer N and a digit d (0–9), find the largest integer x such that 0 ≤ x < N and the decimal
representation of x does not contain digit d. Return -1 if none exists.
Approach 1 — Brute Force Decrement
Java
public class LargestWithoutDigit_Brute {
public static int solve(int N,int d){
String bad=String.valueOf(d);
for (int x=N-1; x>=0; x--)
if (!String.valueOf(x).contains(bad)) return x;
return -1;
}
}
JavaScript
function largestWithoutDigitBrute(N,d){
const bad=String(d);
for (let x=N-1;x>=0;x--) if (!String(x).includes(bad)) return x;
return -1;
}
Explanation
Walk downwards from N−1 until a valid number is found; simple and often fast if the nearest valid is close.
Time & Space Complexity
Worst■case Time O(gap × digits); Space O(1).
Approach 2 — DP–Memo (Digit DP)
Java
import java.util.*;
public class LargestWithoutDigit_Memo {
static class State{int pos; boolean tight; boolean started; State(int p,boolean t,boolean s){pos=p;tight=t;sta
public static int solve(int N,int d){
char[] digits = String.valueOf(N-1).toCharArray();
Integer[][][] memo = new Integer[digits.length+1][2][2];
return dfs(digits,0,true,false,d,memo);
}
private static int dfs(char[] dig,int pos,boolean tight,boolean started,int banned,Integer[][][] memo){
if (pos==dig.length) return 0;
if (memo[pos][tight?1:0][started?1:0]!=null) return memo[pos][tight?1:0][started?1:0];
int limit = tight ? dig[pos]-'0' : 9;
int best = -1;
for (int x=limit; x>=0; x--){
if (started && x==banned) continue;
boolean nStarted = started || x!=0;
if (!nStarted){ // still leading zeros
int rest = dfs(dig,pos+1, tight && x==limit, false, banned, memo);
if (rest!=-1) best = Math.max(best, rest);
} else {
int rest = dfs(dig,pos+1, tight && x==limit, true, banned, memo);
if (rest!=-1){
long candidate = (long)x * (long)Math.pow(10, dig.length-pos-1) + rest;
if (candidate<=Integer.MAX_VALUE) best = (int)Math.max(best, candidate);
}
}
}
return memo[pos][tight?1:0][started?1:0]=best;
}
}
JavaScript
function largestWithoutDigitMemo(N,d){
const s=String(N-1);
const memo = Array.from({length:s.length+1},()=>Array.from({length:2},()=>Array(2)));
function dfs(pos,tight,started){
if (pos===s.length) return 0;
const t=tight?1:0, st=started?1:0;
if (memo[pos][t][st]!==undefined) return memo[pos][t][st];
const limit = tight ? Number(s[pos]) : 9;
let best = -1;
for (let x=limit; x>=0; x--){
if (started && x===d) continue;
const nStarted = started || x!==0;
if (!nStarted){
const rest = dfs(pos+1, tight && x===limit, false);
if (rest!==-1) best = Math.max(best, rest);
}else{
const rest = dfs(pos+1, tight && x===limit, true);
if (rest!==-1){
const pow = 10 ** (s.length-pos-1);
const cand = x*pow + rest;
best = Math.max(best, cand);
}
}
}
return (memo[pos][t][st]=best);
}
return dfs(0,true,false);
}
Explanation
Digit DP chooses digits from most significant to least with a tight upper bound (N−1). State parameters: position,
tight (whether we are equal to the prefix of N−1), and whether the number has started (to handle leading zeros).
We skip the banned digit once the number has started. The transition assembles the maximum valid value.
Time & Space Complexity
Time O(digits×10×state) ≈ O(10·D); Space O(D) for recursion + memo.
Approach 3 — DP–Tab (Iterative Digit DP)
Java
/* Iterative digit-DP table is possible but verbose: dp[pos][tight][started] = best suffix value.
For interview practicality, the memoized version above is clearer and less error-prone. */
JavaScript
/* Same note as Java: tabulation is doable by iterating pos from last to first and enumerating digits,
carrying 'tight' transitions. Omitted for brevity; prefer memoized top-down for clarity. */
Explanation
Bottom■up digit DP mirrors the memo version but fills states from the end toward the front. It’s more mechanical
and longer to code; interviews usually accept the memoized digit DP.
Time & Space Complexity
Time/Space similar to memo.
Approach 4 — Greedy (Digit Repair Heuristic)
Java
public class LargestWithoutDigit_Greedy {
public static String solve(String N,int d){
char ban=(char)('0'+d);
char[] a=String.valueOf(Integer.parseInt(N)-1).toCharArray();
for (int i=0;i<a.length;i++){
if (a[i]==ban){
int j=i;
while (j>=0){
if (a[j]>'0'){
a[j]--; if (a[j]==ban) a[j]--;
for (int k=j+1;k<a.length;k++) a[k]=(ban=='9')?'8':'9';
return stripLeadingZeros(new String(a));
}
j--;
}
// if we couldn't decrease, the answer is all 9/8 of smaller length
StringBuilder sb=new StringBuilder();
for (int k=0;k<a.length-1;k++) sb.append(ban=='9'?'8':'9');
return sb.length()==0? "-1": sb.toString();
}
}
return stripLeadingZeros(new String(a));
}
private static String stripLeadingZeros(String s){
int i=0; while (i<s.length()-1 && s.charAt(i)=='0') i++;
return s.substring(i);
}
}
JavaScript
function largestWithoutDigitGreedy(N,d){
const ban=String(d);
let a = String(Number(N)-1).split("");
for (let i=0;i<a.length;i++){
if (a[i]===ban){
let j=i;
while (j>=0){
if (a[j]>'0'){
a[j]=String.fromCharCode(a[j].charCodeAt(0)-1);
if (a[j]===ban) a[j]=String.fromCharCode(a[j].charCodeAt(0)-1);
for (let k=j+1;k<a.length;k++) a[k]=(ban==='9'?'8':'9');
return strip(a.join(""));
}
j--;
}
const fill = ban==='9'?'8':'9';
return a.length>1 ? fill.repeat(a.length-1) : "-1";
}
}
return strip(a.join(""));
function strip(s){ return s.replace(/^0+(?=\d)/,""); }
}
Explanation
Scan digits from most significant. On encountering the banned digit, decrease a higher-order digit (skipping to
avoid the banned digit after decrement) and fill the suffix with the largest allowed digit (9 or 8 if 9 is banned). This
heuristic works in practice and runs in O(D), though careful handling of carry/leading zeros is required.
Time & Space Complexity
Time O(D); Space O(D).
14. Find All Pairs With Given Sum
Problem Statement
Given an integer array A and a target T, return all unique pairs (x, y) from A such that x + y = T. If order doesn’t
matter, (x, y) and (y, x) are considered the same.
Approach 1 — Brute Force All Pairs
Java
import java.util.*;
public class Pairs_Brute {
public static List<int[]> pairs(int[] a,int T){
List<int[]> res=new ArrayList<>();
Set<String> seen=new HashSet<>();
for (int i=0;i<a.length;i++)
for (int j=i+1;j<a.length;j++)
if (a[i]+a[j]==T){
int x=a[i], y=a[j];
String key = x<=y? x+":"+y : y+":"+x;
if (seen.add(key)) res.add(new int[]{x,y});
}
return res;
}
}
JavaScript
function pairsBrute(arr,T){
const res=[], seen=new Set();
for (let i=0;i<arr.length;i++)
for (let j=i+1;j<arr.length;j++)
if (arr[i]+arr[j]===T){
const [x,y]=[arr[i],arr[j]];
const key = x<=y ? `${x}:${y}` : `${y}:${x}`;
if (!seen.has(key)){ seen.add(key); res.push([x,y]); }
}
return res;
}
Explanation
Try all O(n²) pairs; use a set of canonicalized keys to avoid duplicates if the array has repeated numbers.
Time & Space Complexity
Time O(n^2); Space O(u) for unique pairs.
Approach 2/3 — DP–Memo & DP–Tab (Not Applicable)
Java
// This is a direct selection problem; DP is not needed for the 2-sum variant.
JavaScript
// DP is useful for subset-sum/k-sum counts, not for simple 2-sum pair listing.
Explanation
DP does not simplify listing 2-sum pairs; hashing is optimal.
Time & Space Complexity
—
Approach 4 — Greedy Two-Pointer (After Sorting)
Java
import java.util.*;
public class Pairs_Greedy {
public static List<int[]> pairs(int[] a,int T){
Arrays.sort(a);
List<int[]> res=new ArrayList<>();
int i=0, j=a.length-1;
while(i<j){
int s=a[i]+a[j];
if (s==T){
res.add(new int[]{a[i],a[j]});
int x=a[i], y=a[j];
while(i<j && a[i]==x) i++;
while(i<j && a[j]==y) j--;
} else if (s<T) i++; else j--;
}
return res;
}
}
JavaScript
function pairsGreedy(arr,T){
const a=[...arr].sort((x,y)=>x-y);
const res=[];
let i=0,j=a.length-1;
while(i<j){
const s=a[i]+a[j];
if (s===T){
res.push([a[i],a[j]]);
const x=a[i], y=a[j];
while(i<j && a[i]===x) i++;
while(i<j && a[j]===y) j--;
}else if (s<T) i++; else j--;
}
return res;
}
Explanation
Sort and sweep with two pointers. Greedy movement: if sum is too small, advance left; if too large, retreat right.
De■duplicate by skipping equal neighbors.
Time & Space Complexity
Time O(n log n) for sort; Space O(1) extra (beyond output).
15. Count Continuous Subarrays With Sum K
Problem Statement
Given an integer array A and an integer K, count the number of continuous subarrays whose sum equals K.
Negative numbers are allowed.
Approach 1 — Brute Force (All Subarrays)
Java
public class SubarraySumK_Brute {
public static int count(int[] a,int K){
int n=a.length, cnt=0;
for (int i=0;i<n;i++){
int s=0;
for (int j=i;j<n;j++){
s+=a[j];
if (s==K) cnt++;
}
}
return cnt;
}
}
JavaScript
function countSubarraysBrute(a,K){
let cnt=0;
for (let i=0;i<a.length;i++){
let s=0;
for (let j=i;j<a.length;j++){
s+=a[j];
if (s===K) cnt++;
}
}
return cnt;
}
Explanation
Enumerate all starts i, expand j and track running sum; increment when sum equals K.
Time & Space Complexity
Time O(n^2); Space O(1).
Approach 2 — DP–Memo (Not Applicable / Not Helpful)
Java
// Direct memoization by (i,sum) is large and unnecessary; prefix-hash is optimal.
JavaScript
// Use the prefix-sum hashmap approach instead of memoizing sums.
Explanation
Memoizing subarray sums doesn’t help because sums vary wildly with negatives; prefix■sum hashing is the
canonical O(n) method.
Time & Space Complexity
—
Approach 3 — DP–Tab (Not Applicable / Not Helpful)
Java
// A 2D dp over i,j to store subarray sums devolves into O(n^2) memory and is worse than the prefix-hash trick.
JavaScript
// Prefer prefix-hash linear pass.
Explanation
Tabulating all subarray sums is O(n^2) space/time and unnecessary.
Time & Space Complexity
—
Approach 4 — Greedy Prefix-Sum + Hash (Optimal)
Java
import java.util.*;
public class SubarraySumK_Hash {
public static int count(int[] a,int K){
Map<Integer,Integer> freq=new HashMap<>();
freq.put(0,1);
int s=0, cnt=0;
for (int x: a){
s+=x;
cnt += freq.getOrDefault(s-K,0);
freq.put(s, freq.getOrDefault(s,0)+1);
}
return cnt;
}
}
JavaScript
function countSubarraysHash(a,K){
const freq=new Map(); freq.set(0,1);
let s=0, cnt=0;
for (const x of a){
s+=x;
cnt += (freq.get(s-K)||0);
freq.set(s, (freq.get(s)||0)+1);
}
return cnt;
}
Explanation
Maintain prefix sum s and a frequency map of seen sums. For current s, any earlier prefix equal to s−K starts a
subarray summing to K. Initialize freq[0]=1 for the empty prefix. Works with negatives.
Time & Space Complexity
Time O(n); Space O(n).
16. Remove Duplicate Elements From An Array (Preserve
First Occurrence Order)
Problem Statement
Given an integer array A, remove duplicates so that only the first occurrence of each value remains (stable
order). Return the array of unique elements in order.
Approach 1 — Brute Force (Check Prior Existence)
Java
import java.util.*;
public class Unique_Brute {
public static int[] unique(int[] a){
List<Integer> out=new ArrayList<>();
for (int i=0;i<a.length;i++){
boolean seen=false;
for (int j=0;j<i;j++) if (a[j]==a[i]){ seen=true; break; }
if (!seen) out.add(a[i]);
}
return out.stream().mapToInt(x->x).toArray();
}
}
JavaScript
function uniqueBrute(a){
const out=[];
for (let i=0;i<a.length;i++){
let seen=false;
for (let j=0;j<i;j++) if (a[j]===a[i]){ seen=true; break; }
if (!seen) out.push(a[i]);
}
return out;
}
Explanation
For each element, scan earlier portion to ensure it hasn’t appeared. Preserves first occurrence order naturally.
Time & Space Complexity
Time O(n^2); Space O(n) for output.
Approach 2/3 — DP–Memo & DP–Tab (Not Applicable)
Java
// No overlapping subproblems; this is a filtering task.
JavaScript
// DP is unnecessary here.
Explanation
No DP benefit; the operation is a simple membership check across the seen set.
Time & Space Complexity
—
Approach 4 — Greedy/Hash-Set (One Pass, Stable)
Java
import java.util.*;
public class Unique_Greedy {
public static int[] unique(int[] a){
Set<Integer> seen=new LinkedHashSet<>();
for (int x: a) seen.add(x);
return seen.stream().mapToInt(i->i).toArray();
}
}
JavaScript
function uniqueGreedy(a){
const seen=new Set(), out=[];
for (const x of a){ if (!seen.has(x)){ seen.add(x); out.push(x); } }
return out;
}
Explanation
Greedy accept first occurrence and reject later duplicates using a set; preserves order by pushing only on first
sight.
Time & Space Complexity
Time O(n); Space O(n).
17. Check Whether A Given Number Is Binary (Decimal
Digits only 0/1)
Problem Statement
Given a non-negative integer n (in decimal form), determine if every digit is either 0 or 1.
Approach 1 — Brute (Digit Peeling)
Java
public class IsBinary_Brute {
public static boolean isBinary(long n){
if (n==0) return true;
n=Math.abs(n);
while(n>0){
long d=n%10; if (d!=0 && d!=1) return false;
n/=10;
}
return true;
}
}
JavaScript
function isBinaryBrute(n){
if (n===0) return true;
n=Math.abs(n);
while(n>0){
const d=n%10;
if (d!==0 && d!==1) return false;
n=Math.floor(n/10);
}
return true;
}
Explanation
Check each decimal digit by modulus/division; quick and constant extra space.
Time & Space Complexity
Time O(d) where d=#digits; Space O(1).
Approach 2/3 — DP–Memo & DP–Tab (Not Applicable)
Java
// No substructure; simple digit test.
JavaScript
// DP gives no advantage here.
Explanation
Not a DP problem; it’s a direct property check.
Time & Space Complexity
—
Approach 4 — Greedy (Not Applicable)
Java
// Greedy has no meaningful role here.
JavaScript
// N/A.
Explanation
Greedy selection doesn’t apply to per-digit validation.
Time & Space Complexity
—
18. Check Whether One String Is A Rotation Of Another
Problem Statement
Given two strings s1 and s2, determine if s2 is a rotation of s1 (i.e., s2 can be obtained by some number of cyclic
left shifts of s1).
Approach 1 — Brute Force (Rotate s1 In All Ways)
Java
public class Rotation_Brute {
public static boolean isRotation(String a,String b){
if (a.length()!=b.length()) return false;
int n=a.length();
for (int k=0;k<n;k++){
// rotate left by k
String r = a.substring(k)+a.substring(0,k);
if (r.equals(b)) return true;
}
return false;
}
}
JavaScript
function isRotationBrute(a,b){
if (a.length!==b.length) return false;
const n=a.length;
for (let k=0;k<n;k++){
const r = a.slice(k)+a.slice(0,k);
if (r===b) return true;
}
return false;
}
Explanation
Generate each rotation by slicing/concatenation and compare. Useful to understand definition of rotation.
Time & Space Complexity
Time O(n^2) due to O(n) rotations × O(n) compare; Space O(n).
Approach 2/3 — DP–Memo & DP–Tab (Not Applicable)
Java
// Not a DP optimization problem; we check a string property.
JavaScript
// DP adds no benefit here.
Explanation
DP is not required; the problem has a direct linear-time trick.
Time & Space Complexity
—
Approach 4 — Greedy/Trick: Substring of (s1 + s1)
Java
public class Rotation_Trick {
public static boolean isRotation(String a,String b){
return a.length()==b.length() && (a+a).contains(b);
}
}
JavaScript
function isRotation(a,b){
return a.length===b.length && (a+a).includes(b);
}
Explanation
Observation: any rotation of a appears as a substring in a+a. This leads to an O(n) (or O(n) expected) check
depending on substring algo. In many languages, `.contains`/`.includes` is O(n) average.
Time & Space Complexity
Time O(n); Space O(n) for concatenation.
19. Find Intersection Of Two Arrays (Unique Elements)
Problem Statement
Given two integer arrays A and B, return the set of elements that appear in both (uniquely, no duplicates in
result).
Approach 1 — Brute Force (Nested Search)
Java
import java.util.*;
public class Intersect_Brute {
public static int[] intersect(int[] A,int[] B){
Set<Integer> res=new LinkedHashSet<>();
for (int x: A){
for (int y: B){
if (x==y){ res.add(x); break; }
}
}
return res.stream().mapToInt(i->i).toArray();
}
}
JavaScript
function intersectionBrute(A,B){
const res=new Set();
for (const x of A){
for (const y of B){
if (x===y){ res.add(x); break; }
}
}
return [...res];
}
Explanation
Compare each element of A with every element of B; stop early after a match to avoid duplicates in output.
Time & Space Complexity
Time O(nm); Space O(min(n,m)) for result.
Approach 2/3 — DP–Memo & DP–Tab (Not Applicable)
Java
// Intersection is a set membership problem; DP is not needed.
JavaScript
// N/A.
Explanation
DP doesn’t reduce complexity here; hashing is optimal.
Time & Space Complexity
—
Approach 4 — Greedy/Hash-Set
Java
import java.util.*;
public class Intersect_Greedy {
public static int[] intersect(int[] A,int[] B){
Set<Integer> s=new HashSet<>(); for (int x: A) s.add(x);
Set<Integer> ans=new LinkedHashSet<>();
for (int y: B) if (s.contains(y)) ans.add(y);
return ans.stream().mapToInt(i->i).toArray();
}
}
JavaScript
function intersection(A,B){
const set=new Set(A), ans=[], seen=new Set();
for (const y of B){
if (set.has(y) && !seen.has(y)){ ans.push(y); seen.add(y); }
}
return ans;
}
Explanation
Load one array into a set and test membership for the other; use an insertion-ordered set (or extra set) to keep
unique elements without repeats.
Time & Space Complexity
Time O(n+m); Space O(n+m).
20. Check Whether Input String Is A Number
Problem Statement
Given an input string s, determine if it represents a valid finite number (integers or decimals, optional sign,
optional exponent). Whitespace around the number may be ignored.
Approach 1 — Brute (Manual State Parsing)
Java
public class IsNumber_Brute {
public static boolean isNumber(String s){
if (s==null) return false;
s=s.trim();
if (s.isEmpty()) return false;
// Very simple manual parser: sign, digits, optional dot+digits, optional exponent
int i=0,n=s.length();
if (i<n && (s.charAt(i)=='+' || s.charAt(i)=='-')) i++;
boolean digits=false, dot=false;
while (i<n && Character.isDigit(s.charAt(i))){ i++; digits=true; }
if (i<n && s.charAt(i)=='.'){ dot=true; i++; while (i<n && Character.isDigit(s.charAt(i))){ i++; digits=tr
if (!digits) return false;
if (i<n && (s.charAt(i)=='e' || s.charAt(i)=='E')){
i++;
if (i<n && (s.charAt(i)=='+' || s.charAt(i)=='-')) i++;
boolean expDigits=false;
while (i<n && Character.isDigit(s.charAt(i))){ i++; expDigits=true; }
if (!expDigits) return false;
}
return i==n;
}
}
JavaScript
function isNumberBrute(s){
if (s==null) return false;
s=String(s).trim();
if (!s) return false;
let i=0, n=s.length;
if (s[i]==='+'||s[i]==='-') i++;
let digits=false;
while (i<n && s[i]>='0'&&s[i]<='9'){ i++; digits=true; }
if (i<n && s[i]==='.') { i++; while (i<n && s[i]>='0'&&s[i]<='9'){ i++; digits=true; } }
if (!digits) return false;
if (i<n && (s[i]==='e'||s[i]==='E')){
i++; if (i<n && (s[i]==='+'||s[i]==='-')) i++;
let exp=false; while (i<n && s[i]>='0'&&s[i]<='9'){ i++; exp=true; }
if (!exp) return false;
}
return i===n;
}
Explanation
Implements a minimal deterministic scan: optional sign → digits → optional fractional part → optional exponent
(with optional sign). This covers most numeric literals for interviews without using libraries.
Time & Space Complexity
Time O(n); Space O(1).
Approach 2/3 — DP–Memo & DP–Tab (Not Applicable)
Java
// While you can model this as a finite automaton, DP isn't needed; a single pass is sufficient.
JavaScript
// N/A.
Explanation
Parsing here is a regular-language task (DFA). DP is not required for correctness or efficiency.
Time & Space Complexity
—
Approach 4 — Greedy/Library Parser (Pragmatic)
Java
public class IsNumber_Library {
public static boolean isNumber(String s){
if (s==null) return false;
try { Double.parseDouble(s.trim()); return Double.isFinite(Double.parseDouble(s.trim())); }
catch(NumberFormatException e){ return false; }
}
}
JavaScript
function isNumberLibrary(s){
if (s==null) return false;
const x=Number(String(s).trim());
return Number.isFinite(x);
}
Explanation
Use built-in numeric parser and ensure the result is finite. This is pragmatic and handles many edge cases;
behavior is implementation-defined for exotic formats.
Time & Space Complexity
Time O(n) parse; Space O(1).