0% found this document useful (0 votes)
5 views33 pages

Ilovepdf Merged Compressed

pdf

Uploaded by

dhrugenai12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views33 pages

Ilovepdf Merged Compressed

pdf

Uploaded by

dhrugenai12
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Visteon Coding Patterns - Step by Step

10 high-yield coding patterns for MyAnatomy / HackerEart with


sample I/O, step-by-step reasoning, and clean Pytho

Use this as a last-minute revision kit.


# Pattern 1: Digit Confusion (5 6) Min & Max Sum

Problem:
Given two integers A and B. Due to dyslexia, digit '5' may be '6' and '6' may be '5'. Print two values:
(min_possible_sum, max_possible_sum).
Min: treat every 6 as 5. Max: treat every 5 as 6.

Input:
53 64
Output:
107 127

Step-by-step (for 53 64):


- Min (6 5):
A="53" -> "53" -> 53
B="64" -> "54" -> 54
Min sum = 53 + 54 = 107
- Max (5 6):
A="53" -> "63" -> 63
B="64" -> "64" -> 64
Max sum = 63 + 64 = 127

Python (input on one line):


```python
a, b = input().split()

amin = int(''.join('5' if ch == '6' else ch for ch in a)) bmin =


int(''.join('5' if ch == '6' else ch for ch in b))

amax = int(''.join('6' if ch == '5' else ch for ch in a)) bmax =


int(''.join('6' if ch == '5' else ch for ch in b))

print(amin + bmin, amax + bmax)


```
# Pattern 2: Normalize + Palindrome (ignore spaces/punct/case)

Problem:
Given a string S, check if it s a palindrome after removing non-alphanumeric chars and ignoring
case. Print "YES" or "NO".

Input:
A man, a plan, a canal: Panama
Output:
YES

Step-by-step:
- Normalize: keep only letters/digits, to lower-case.
- Compare normalized string with its reverse.

Python:
```python
import sys
import re

s = sys.stdin.read().strip()
norm = re.sub(r'[^A-Za-z0-9]', '', s).lower() print("YES" if norm
== norm[::-1] else "NO")
```
# Pattern 3: Rotate Array Right by K

Problem:
Given N and K, then an array of N integers, rotate array to the right by K and print.

Input:
52
12345
Output:
45123

Step-by-step:
- Effective K = K % N
- Right rotate: last K elements come to front; rest follow.

Python:
```python
n, k = map(int, input().split())
arr = list(map(int, input().split())) k %= n
rotated = arr[-k:] + arr[:-k] if k else arr print(*rotated)
```
# Pattern 4: Count Subarrays with Sum = K (Prefix Sum + HashMap)

Problem:
Given N, K and array A, count number of subarrays that sum to K.

Input:
57
23431
Output:
2

Step-by-step (prefix sums):


- Maintain running sum 'cur' and a dict 'freq' of prefix sums seen.
- For each value x:
cur += x
We need previous prefix 'cur - K' to form a subarray sum K. Add freq[cur
- K] to answer. Then increment freq[cur].

Python:
```python
from collections import defaultdict

n, k = map(int, input().split())
arr = list(map(int, input().split()))

freq = defaultdict(int) freq[0] = 1


cur = 0
ans = 0

for x in arr:
cur += x
ans += freq[cur - k]
freq[cur] += 1

print(ans)
```
# Pattern 5: Anagram Check (two strings)

Problem:
Given two strings s and t, check if t is an anagram of s (ignore spaces/case). Print YES/NO.

Input:
Dormitory
Dirty room
Output:
YES

Step-by-step:
- Normalize both strings: keep letters only, same case.
- Compare frequency counts OR sorted strings.

Python (frequency map):


```python
import re
from collections import Counter

s = re.sub(r'[^A-Za-z]', '', input()).lower()


t = re.sub(r'[^A-Za-z]', '', input()).lower()

print("YES" if Counter(s) == Counter(t) else "NO")


```
# Pattern 6: Balanced Parentheses (Stack)

Problem:
Given a string with '()[]{}', determine if it's valid (properly nested).

Input:
{[()]}
Output:
YES

Step-by-step:
- Use stack.
- For each opening, push.
- For each closing, pop and check matching pair.

Python:
```python
pairs = {')':'(', ']':'[', '}':'{'}
s = input().strip() stack
= []
ok = True for
ch in s:
if ch in '([{': stack.append(ch)
else:
if not stack or stack[-1] != pairs.get(ch, '#'): ok = False
break
stack.pop()
if stack: ok = False print("YES" if
ok else "NO")
```
# Pattern 7: GCD and LCM of a List

Problem:
Read N and a list. Print gcd and lcm of all numbers.

Input:
4
2 4 8 16
Output:
2 16

Step-by-step:
- gcd(a,b) via math.gcd.
- lcm(a,b) = a*b // gcd(a,b).
- Reduce across the list.

Python:
```python
import math

n = int(input())
arr = list(map(int, input().split()))

g = arr[0] l
= arr[0]
for x in arr[1:]:
g = math.gcd(g, x)
l = l * x // math.gcd(l, x)

print(g, l)
```
# Pattern 8: DP Climbing Stairs (1 or 2 steps)

Problem:
Given n, number of distinct ways to reach the top if you can climb 1 or 2 steps at a time.

Input:
5
Output:
8

Step-by-step:
- dp[0]=1 (1 way to stand on ground), dp[1]=1.
- dp[i]=dp[i-1]+dp[i-2].

Python:
```python
n = int(input()) if n
<= 1:
print(1)
else:
a, b = 1, 1 # dp[i-2], dp[i-1] for _ in
range(2, n+1):
a, b = b, a+b
print(b)
```
# Pattern 9: DP Minimum Path Sum in Grid

Problem:
Given rows, cols and the grid, move only right or down. Print min path sum from (0,0) to (r-1,c-1).

Input:
33
131
151
421
Output:
7

Step-by-step:
- dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1])
- Initialize first row/col by cumulative sums.

Python:
```python
r, c = map(int, input().split())
grid = [list(map(int, input().split())) for _ in range(r)]

dp = [[0]*c for _ in range(r)] dp[0]


[0] = grid[0][0]

for j in range(1, c):


dp[0][j] = dp[0][j-1] + grid[0][j] for i in
range(1, r):
dp[i][0] = dp[i-1][0] + grid[i][0] for i in
range(1, r):
for j in range(1, c):
dp[i][j] = grid[i][j] + min(dp[i-1][j], dp[i][j-1])

print(dp[-1][-1])
```
# Pattern 10: First Non-Repeating Character

Problem:
Given a string s, print the index (0-based) of the first non-repeating character. If none, print -1.

Input:
leetcode
Output:
0

Step-by-step:
- Count frequency of each char.
- Scan string; return first index with freq=1.

Python:
```python
from collections import Counter

s = input().strip() freq =
Counter(s) ans = -1
for i, ch in enumerate(s): if
freq[ch] == 1:
ans = i
break
print(ans)
```
Great — here are detailed, step-by-step solutions for the 10 Java questions
(the full reasoning you can use for interviews or placement tests). For each
snippet I’ll explain what every part does, show a precise execution trace, point
out common pitfalls, and give the final output.

Java — Detailed step-by-step solutions

Q1 — Abstract class (basic)


abstract class
Shape { abstract
void draw();
}

class Circle extends Shape


{ void draw() {
System.out.println("Drawing Circle");
}
}

public class Test {


public static void main(String[]
args) { Shape s = new Circle();
s.draw();
}
}

Concepts (from scratch)

abstract class Shape declares a class that may include abstract methods and
cannot be instantiated directly.

abstract void draw(); is a method declaration without a body — subclasses


must provide an implementation.
class Circle extends Shape provides the concrete implementation.

Shape s = new Circle(); demonstrates polymorphism: the reference type is


Shape, runtime object is Circle.

Method calls on instance methods are dynamically dispatched (runtime


decides which draw() to call).

Line-by-line / execution trace

1.
Class loading: JVM loads Shape, Circle, and Test into the method area (class
metadata).

2.
main() starts on the stack.

3.
new Circle():

JVM allocates a Circle object on the heap.

If any default constructors exist, they run (here implicit).

4.
The returned Circle reference is stored in variable s of compile-time type
Shape.
5.
s.draw() is invoked:

At runtime JVM finds Circle's draw() (because of dynamic dispatch) and


executes it.

System.out.println("Drawing Circle") prints to stdout.

Output

Drawing Circle

Notes / Pitfalls

You cannot do new Shape() because Shape is abstract.

If Circle did not override draw(), compilation would fail.

This is single-method polymorphism; works the same for multiple methods.

Q2 — Abstract class with constructors


abstract class Base {
Base() { System.out.println("Base Constructor");
} abstract void fun();
}

class Derived extends Base {


Derived() { System.out.println("Derived
Constructor"); } void fun() {
System.out.println("Fun in Derived"); }
}

public class Test {


public static void main(String[]
args) { Base b = new
Derived();
b.fun();
}
}

Concepts (from scratch)

Abstract classes can have constructors. They run when a subclass instance is
created.

Constructors execute in inheritance order: superclass constructor first, then


subclass constructor.

new Derived() implicitly calls super() (the no-arg Base constructor) at start of
Derived() unless explicit call provided.

Execution trace

1.
JVM loads classes.

2.
main() runs.

3.
new Derived():

Enter Derived() constructor.

Implicit super() call executes Base() constructor:

prints: Base Constructor.

Return to Derived() constructor body:

prints: Derived Constructor.

4.
The Derived object reference is assigned to b with compile type Base.

5.
b.fun() calls Derived's overridden fun():

prints: Fun in Derived.

Output

Base Constructor
Derived
Constructor Fun in
Derived

Notes

Even though Base is abstract, its constructor still runs when a concrete
subclass is instantiated.

If Base had a parameterized constructor only (no no-arg), you must call
super(args) explicitly from Derived().

Q3 — String pool, == vs equals()


public class Test {
public static void main(String[]
args) { String s1 = "hello";
String s2 = "hello";
String s3 = new String("hello");

System.out.println(s1 == s2);
System.out.println(s1 == s3);
System.out.println(s1.equals(s3))
;
}
}

Concepts (from scratch)

Java maintains a String literal pool (intern pool). String literals like "hello" are
stored once in the pool.
String s1 = "hello"; and String s2 = "hello"; both reference the same pooled
object.

new String("hello") creates a new distinct object on the heap (even though it
may internally reference the pooled literal).

== checks reference equality (are they the same object?). equals() (String's
override) checks value equality (same sequence of characters).

Execution trace

1.
When class loads, the literal "hello" is placed in the string pool (if not already
present).

2.
s1 points to pooled "hello".

3.
s2 also points to the same pooled "hello".

4.
new String("hello") allocates a new String object on the heap whose character
content is "hello"; s3 points to that new object.

5.
s1 == s2 □ true (same pooled reference).

6.
s1 == s3 □ false (different references: pool vs new heap object).

7.
s1.equals(s3) □ true (content equals).
Output

true
fals
e
true

Extra tips

You can force s3 to refer to the pool with s3 = s3.intern(); then s1 == s3


becomes true.

Beware of using == for strings in interview code — it tests reference


equality, not value equality.

Q4 — Method overriding (dynamic


dispatch)
class A {
void show() { System.out.println("A"); }
}
class B extends A {
void show() { System.out.println("B"); }
}
public class Test {
public static void main(String[]
args) { A obj = new B();
obj.show();
}
}

Concepts (from scratch)


B overrides show() from A.

A obj = new B(); : reference type A, object of runtime type B.

For instance methods, Java uses dynamic dispatch: the runtime type decides
which overridden method is executed.

Execution trace

1.
new B() creates object of type B on heap.

2.
obj (type A) references that B object.

3.
obj.show():

JVM looks at runtime type (B), finds B.show(), and invokes it.

prints: B.

Output

B
Pitfall

If show() were static, then the call would be resolved at compile time using
the reference type (A.show()), not runtime type. Static methods are not
overridden.

Q5 — Interface and implements


interface
Animal {
void sound();
}
class Dog implements
Animal { public void
sound() {
System.out.println("Woof");
}
}
public class Test {
public static void main(String[]
args) { Animal a = new Dog();
a.sound();
}
}

Concepts (from scratch)

interface Animal declares sound(); by default (pre-Java 9) methods are public


abstract.

Dog implements Animal — it must implement sound() and the method


must be public (visibility cannot be reduced).
Animal a = new Dog(); demonstrates polymorphism with interfaces.
Execution trace

1.
new Dog() creates Dog object.

2.
Reference a of interface type Animal points to Dog object.

3.
a.sound() dynamically dispatches to Dog.sound():

prints Woof.

Output

Woof

Notes

In modern Java, interfaces can also contain default and static methods, but the
requirement to implement abstract methods remains.

If you omit public in Dog.sound() you get a compile error because interface
methods are public.
Q6 — Static block vs main()
class Test {
static {
System.out.println("Static Block");
}
public static void main(String[]
args)
{ System.out.println("Main
Method");
}
}

Concepts (from scratch)

Static blocks (static initializers) execute when the class is initialized (by the
class loader)
— typically the first time the JVM needs the class (e.g., before main()).

They run once per class, in textual order if multiple static blocks exist.

main() runs after static initializers.

Execution trace

1.
JVM starts and looks for Test.main().

2.
Before invoking main, it initializes class Test:

Executes the static block:


prints Static Block.

3.
Then main() is invoked:

prints Main Method.

Output

Static Block
Main Method

Extra notes

Static field initializers also execute in the same initialization phase in


declaration order.

If class initialization throws an exception, NoClassDefFoundError /


ExceptionInInitializerError may result.

Q7 — Exception handling (try-catch)


public class Test {
public static void main(String[]
args) { try {
int x = 5 / 0;
} catch (ArithmeticException e)
{ System.out.println("Divide by zero");
}
System.out.println("After catch");
}
}

Concepts (from scratch)

5 / 0 on ints causes an ArithmeticException at runtime.

The try block execution halts at the exception and control is transferred to
the matching catch.

After catch executes, normal flow continues (unless exception rethrown).

Execution trace

1.
Enter try block.

2.
Evaluate int x = 5 / 0; □ JVM throws ArithmeticException.

3.
Jump to catch(ArithmeticException e):

prints: Divide by zero.


4.
After catch, execution continues:

prints: After catch.

Output

Divide by zero
After catch

Notes

If no matching catch existed, exception would propagate and possibly


terminate the program.

finally block (if present) runs regardless of whether an exception occurred


(except in very rare termination scenarios).

Q8 — Tricky for-loop (semicolon)


public class Test {
public static void main(String[]
args) { int i = 0;
for(; i < 3; i++);
System.out.println(i);
}
}

Concepts (from scratch)

A for loop of the form for(init; condition; update); has a ; as the body □
empty loop body.

The loop still runs the condition and update, but no statements are executed
inside the body.

i is declared outside the loop, so it is accessible afterward.

Execution trace

1.
i initialized to 0.

2.
Loop iteration 1: check i < 3 □ 0 < 3 true □ body is empty □ execute i++ □ i
= 1.

3.
Iteration 2: 1 < 3 true □ i++ □ i = 2.

4.
Iteration 3: 2 < 3 true □ i++ □ i = 3.

5.
Iteration 4: 3 < 3 false □ loop ends.

6.
System.out.println(i) prints current i, which is 3.
Output

Pitfall

A common mistake is to place ; after for(...) inadvertently and wonder why


loop body didn’t run.

Q9 — final variable basics


class Test {
public static void main(String[]
args) { final int x = 10;
// x = 20; // error
System.out.println(x);
}
}

Concepts (from scratch)

final makes a variable a constant: it can be assigned once.

For primitives, final prevents reassignment.

For reference types, final prevents reassigning the reference, but you can
still mutate the object's internal state.
Execution trace

1.
final int x = 10; assigns 10 to x.

2.
System.out.println(x) prints 10.

Output

10

Notes

Attempting x = 20; is a compile-time error: “cannot assign a value to final


variable x”.

final local variables must be definitely assigned before use.

Q10 — Multiple subclasses & polymorphism


abstract class
Shape { abstract
void draw();
}
class Circle extends Shape {
void draw() { System.out.println("Circle"); }
}
class Square extends Shape {
void draw() { System.out.println("Square"); }
}
public class Test {
public static void main(String[]
args) { Shape s1 = new
Circle();
Shape s2 = new
Square(); s1.draw();
s2.draw();
}
}

Concepts (from scratch)

Multiple concrete subclasses implement the same abstract method in different


ways.

Polymorphism lets you work with Shape references and call draw(); runtime
chooses the correct implementation based on the object’s type.

Execution trace

1.
new Circle() □ create Circle object; assigned to s1.

2.
new Square() □ create Square object; assigned to s2.

3.
s1.draw() □ runtime picks Circle.draw() □ prints Circle.

4.
s2.draw() □ runtime picks Square.draw() □ prints Square.
Output

Circle
Square

Interview note

This pattern supports open-closed design: you can add new Shape subclasses
without changing existing code that uses Shape.

Quick summary: what to remember (


Java interviews)

Abstract vs interface: abstract classes can have state and constructors;


interfaces are contracts ( Java 8+ interfaces can have default and static
methods).

== checks reference identity; .equals() checks logical equality (implement


equals() correctly).

Polymorphism: reference type vs runtime type — instance method calls are


resolved at runtime.

Static initializers and fields run at class initialization time (once).

Exceptions transfer control flow — try □ catch □ finally as applicable.


Final applies to variables (constant), methods (cannot be overridden), classes
(cannot be subclassed).

Watch out for common pitfalls: for(…); stray semicolons, mutable default
arguments (Python), new String() vs pool for strings, static vs instance
method dispatch.

If you want, I can:

Convert these Java explanations into a single PDF (well formatted) — I can
generate it now and provide a download link, or

Expand any specific question even further (e.g., show memory diagram with
stack/heap/ method area for a particular example), or

Do the same depth of step-by-step explanation for the C and Python sections
next.

Which would you like next?

You might also like