0% found this document useful (0 votes)
4 views

Interview Coding Questions

The document contains three programming problems: the first involves finding a fair subsequence from an array of integers that alternates between positive and negative numbers while maximizing the sum; the second counts the number of palindromic substrings in a given string; and the third checks if a jet plane returns to its starting position based on directional inputs. Each problem includes a detailed explanation, example test cases, and approaches to solve them. Additionally, code implementations in Python and Java are provided for each problem.

Uploaded by

howtoaddme
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Interview Coding Questions

The document contains three programming problems: the first involves finding a fair subsequence from an array of integers that alternates between positive and negative numbers while maximizing the sum; the second counts the number of palindromic substrings in a given string; and the third checks if a jet plane returns to its starting position based on directional inputs. Each problem includes a detailed explanation, example test cases, and approaches to solve them. Additionally, code implementations in Python and Java are provided for each problem.

Uploaded by

howtoaddme
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 12

Interview Coding Questions

Program 1: Fair Sequence

Description:
You are given an array A of size N. Your friend gave me an amazing task for you.
Your friend likes one type of Sequence. So, he called that type of sequence a fair
sequence. You should select a fair sequence of maximum length from an array. Here
a fair sequence is nothing, but you must select elements in a pattern like positive
element, negative element, positive element… to form a sequence. Your task is to
print the maximum sum of elements possible by selecting a fair subsequence with
maximum length.
Example:
If art A = [-1, 18, 13, 18, -2, 16, 7, -1, -213, 11].
Here your maximum length can be 6.
The fair subsequence is -1, 18,-2, 7, -1, 11.
The Sum is 32 which is the maximum possible.

NOTE: You should select the elements in a fair sequence only.

Test Case 1:
Input: [-1, 18, 13, -2, 16, 7, -1, -213, 11]
Fair Sequence: -1, 18, -2, 7, -1, 11
Sum: -1 + 18 - 2 + 7 - 1 + 11 = 32
Output: 32

Test Case 2:
Input: [5, -1, -3, 10, 15, -8, 2]
Fair Sequence: 5, -1, 10, -3, 15, -8
Sum: 5 - 1 + 10 - 3 + 15 - 8 = 30
Output: 30

Test Case 3:
Input: [-10, -20, -30, -40]
Fair Sequence: [-10]
Sum: -10
Output: -10
(No positive numbers are available, so only one negative number can be selected.)

Test Case 4:
Input: [10, 20, 30, 40]
Fair Sequence: [10]
Sum: 10
(No negative numbers are available, so only one positive number can be selected.)

Test Case 5:
Input: [-1, 1, -2, 2, -3, 3]
Fair Sequence: -1, 1, -2, 2, -3, 3
Sum: -1 + 1 - 2 + 2 - 3 + 3 = 6
Output: 6
Solution: Let us break down the program
Problem Statement States:

You are given an array of integers, which can contain both positive and negative
numbers. Your task is to:
 Select a subsequence of maximum possible length that alternates between
positive and negative numbers.
 Maximize the sum of this subsequence.

What the Program must do:

Subsequence:
A subsequence is a sequence derived from the original array by removing some or
no elements without changing the order of the remaining elements.
For example, in the array [3, -2, 5, -4]:
[3, -2, 5] is a valid subsequence.
[3, 5, -4] is a valid subsequence.
[5, -4, -2] is not a valid subsequence because it changes the order.

Fair Sequence:
A fair sequence alternates between positive and negative elements.
Example 1: [5, -1, 6, -3] (starts with positive, alternates with negative).
Example 2: [-2, 4, -5, 7] (starts with negative, alternates with positive).
The alternation ensures no two consecutive numbers in the subsequence are of the
same sign.

Maximizing the Sum: Among all possible fair sequences, choose the one with the
highest sum of elements.

Example 1:
Input Array: [-1, 18, 13, -2, 16, 7, -1, -213, 11]

Fair Sequence Explanation:


A valid fair sequence must alternate between positive and negative values:
One possible sequence: [-1, 18, -2, 7, -1, 11]
Sum: -1 + 18 - 2 + 7 - 1 + 11 = 32

Another possible sequence: [-1, 13, -2, 16, -1, 7]


Sum: -1 + 13 – 2 + 16 – 1 + 7 = 32
The best sequence (either of the above) has a maximum sum of 32.
Output: The maximum sum is 32.

Example 2:
Input Array: [5, -1, -3, 10, 15, -8, 2]

Fair Sequence Explanation:


A valid fair sequence:
[5, -1, 10, -3, 15, -8] (alternates positive/negative).
Sum: 5 - 1 + 10 - 3 + 15 - 8 = 30.

No other sequence with alternation will produce a larger sum.


Output: The maximum sum is 30.

Example 3:
Input Array: [-10, -20, -30, -40]
Fair Sequence Explanation:
Since all numbers are negative, we can only pick one number (starting the
sequence).
The best choice is the smallest negative number: [-10] (closest to 0).
Output: The maximum sum is -10.

Approach to Solve

1. Sort the Array: Separate the array into positive and negative numbers.
2. Sort Each Group:
a. Positive numbers are sorted in descending order (to maximize
contribution).
b. Negative numbers are sorted in ascending order (closer to zero is less
negative and maximizes the sum).
3. Construct the Sequence:
a. Start with either the largest positive or smallest negative number.
b. Alternate between positive and negative numbers, picking from the
sorted lists.
c. Stop when one of the lists is exhausted.
4. Calculate the Sum:
a. Add all elements in the constructed fair sequence.

Code in Python

Code in Java

----------------------------------------------------------------------------------------

Program 2:

Description:
Given a string s, return the number of palindromic substrings in it.

Test Cases
Input: abc
Output: 3
Explanation: Palindromes  "a", "b", "c"

Input: aaa
Output: 6
Explanation: Palindromes  "a", "a", "a", "aa", "aa", "aaa"

Input: racecar
Output: 10
Explanation: Palindromes  "r", "a", "c", "e", "c", "a", "r", "cec", "aceca", "racecar"

Input: abccba
Output: 9
Explanation: Palindromes  "a", "b", "c", "c", "b", "a", "cc", "bccb", "abccba"

Input: (Empty string)


Output: 0

Solution: Let us break down the program

Palindrome Definition: A substring is a palindrome if s[i] == s[j] for its starting


and ending indices i and j, and the middle part of the substring (if any) is also a
palindrome.
Substring: A contiguous portion of the string. For example, in "abc", substrings
include "a", "b", "c", "ab", "bc", and "abc".
Output: The function should count and return how many of these substrings are
palindromes.

Approach:
The solution uses a centre expansion technique to efficiently count all palindromic
substrings.

Every palindrome has a centre, which can either be:


1. A single character (for odd-length palindromes like "aba").
2. Between two characters (for even-length palindromes like "abba").

The centre expansion technique works by:


1. Iterating over all possible centres (both single-character centres and between-
character centres).
2. Expanding outward from each centre to count palindromes.

Steps:
1. Number of Centres:
o For a string of length nnn:
 There are nnn single-character centers (odd-length palindromes).
 There are n−1n-1n−1 between-character centers (even-length
palindromes).
 In total, there are 2n – 1 centres.
2. Expanding from Each Centre:
o For each centre:
 Expand outward while the characters at the left and right indices
are equal and within bounds.
 For every successful expansion, increment the count of
palindromic substrings.
 Stop expanding when the characters don't match or go out of
bounds.

Example 1: "aaa"
Length of the string: n = 3
Number of Centres: 2n - 1 = 5

Centre 0:
Left and Right Pointers: left = 0, right = 0 (single-character Centre at 'a').
Expansion:
Check s[0] == s[0] → True → Palindrome: "a".
Move pointers outward: left = -1, right = 1 → Out of bounds.
Count: 1 palindrome found.

Centre 1:
Left and Right Pointers: left = 0, right = 1 (between characters 'a' and 'a').
Expansion:
Check s[0] == s[1] → True → Palindrome: "aa".
Move pointers outward: left = -1, right = 2 → Out of bounds.
Count: 1 more palindromes found, total = 2.

Centre 2:
Left and Right Pointers: left = 1, right = 1 (single-character Centre at 'a').
Expansion:
Check s[1] == s[1] → True → Palindrome: "a".
Move pointers outward: left = 0, right = 2.
Check s[0] == s[2] → True → Palindrome: "aaa".
Move pointers outward: left = -1, right = 3 → Out of bounds.
Count: 2 more palindromes found, total = 4.

Centre 3:
Left and Right Pointers: left = 1, right = 2 (between characters 'a' and 'a').
Expansion:
Check s[1] == s[2] → True → Palindrome: "aa".
Move pointers outward: left = 0, right = 3 → Out of bounds.
Count: 1 more palindromes found, total = 5.

Centre 4:
Left and Right Pointers: left = 2, right = 2 (single-character Centre at 'a').
Expansion:
Check s[2] == s[2] → True → Palindrome: "a".
Move pointers outward: left = 1, right = 3 → Out of bounds.
Count: 1 more palindromes found, total = 6.

The palindromic substrings found are:


1. "a" (Centre 0)
2. "aa" (Centre 1)
3. "a" (Centre 2)
4. "aaa" (Centre 2)
5. "aa" (Centre 3)
6. "a" (Centre 4)
Output: 6
Odd-length palindromes: "a", "a", "a", "aaa".
Even-length palindromes: "aa", "aa".

Example 2: "abc"
Length of the string: n = 3
Number of Centers: 2n - 1 = 5

Centres: 5 total centres (0, 1, 2, 3, 4).


Centre 0 (single-character "a"): Palindrome count = 1.
Centre 1 (between "a" and "b"): No palindrome.
Centre 2 (single-character "b"): Palindrome count = 1.
Centre 3 (between "b" and "c"): No palindrome.
Centre 4 (single-character "c"): Palindrome count = 1.
Result: Total palindromes = 3.

Code in Python
class PalindromicSubstrings:
def countSubstrings(self, s: str) -> int:
n = len(s)
count = 0

# Iterate over all possible centers


for center in range(2 * n - 1):
left = center // 2 # Determine the left pointer
# Determine the right pointer for odd/even centers
right = left + center % 2

# Expand outward while the substring is palindromic


while left >= 0 and right < n and s[left] == s[right]:
count += 1 # Count the palindrome
left -= 1 # Move left pointer outward
right += 1 # Move right pointer outward

return count

# Test cases
solution = PalindromicSubstrings()

print(solution.countSubstrings("abc")) # Output: 3 ("a", "b", "c")


print(solution.countSubstrings("aaa")) # Output: 6 ("a", "a", "a", "aa", "aa", "aaa")
print(solution.countSubstrings("racecar")) # Output: 10
print(solution.countSubstrings("abccba")) # Output: 9
print(solution.countSubstrings("")) # Output: 0
print(solution.countSubstrings("a")) # Output: 1

Code in Java
public int countSubstrings(String s)
{
int n = s.length(); // Length of the input string
int count = 0; // Initialize the palindrome count to 0

// Iterate through all possible centres


for (int center = 0; center < 2 * n - 1; center++)
{
// Calculate the left and right pointers
// Integer division gives the actual index for odd/even centers
int left = center / 2;

// Adjust for even-length centres


int right = left + center % 2;

// Expand outward while the substring is palindromic


while (left >= 0 && right < n && s.charAt(left) == s.charAt(right))
{
count++; // Count the palindrome
left--; // Expand leftward
right++; // Expand rightward
}
}

return count;
}

public static void main(String[] args)


{
Main solution = new Main();

// Test cases
System.out.println(solution.countSubstrings("abc"));
// Output: 3 ("a", "b", "c")
System.out.println(solution.countSubstrings("aaa"));
// Output: 6 ("a", "a", "a", "aa", "aa", "aaa")
System.out.println(solution.countSubstrings("racecar"));
// Output: 10
System.out.println(solution.countSubstrings("abccba"));
// Output: 9
System.out.println(solution.countSubstrings(""));
// Output: 0
}
}
----------------------------------------------------------------------------------------
Program 3:

Description:
Find out whether the jet plane returns to the same position from where it took off.

Most modern aircrafts are equipped with an autopilot system – one of the most
useful features in fighter jets. In the beta testing of autopilot mode, one of the
inputs is a string of literals containing the directions, which is fed into the flight
computer before the take-off. The jet plane is put on an auto-landing mode that
enables the plane to land automatically once all the directions in the string are
complete. Given the directions in the string “str”, the task here is to find out
whether the jet plane returns to the same position from where it took off.

Each direction in the string changes at an interval of 1 minute(1< =i<= N), where N
is the number of directions in the input string.
The directions are North (N), South(S), West(W) and East(E).

Output:
"Returned successfully", if the plane returns to the starting position.
"Not returned successfully", if the plane does not return to the starting position.

Test Case 1:
Input: "NNWESW"
Output: "Not returned successfully".
Explanation:
Initialize Displacements:
Horizontal (x-axis) = 0
Vertical (y-axis) = 0

Processing Each Direction:


N:
Move 1 unit up (North).
vertical=0+1=1.
Current position: (x,y)=(0,1).

N:
Move 1 unit up (North).
vertical=1+1=2.
Current position: (x,y)=(0,2).

W:
Move 1 unit left (West).
horizontal=0−1=−1.
Current position: (x,y)=(−1,2).

E:
Move 1 unit right (East).
horizontal=−1+1=0.
Current position: (x,y)=(0,2).

S:
Move 1 unit down (South).
vertical=2−1=1.
Current position: (x,y)=(0,1).

W:
Move 1 unit left (West).
horizontal=0−1=−1.
Current position: (x,y)=(−1,1).

Final Displacement:
Horizontal (x-axis): -1
Vertical (y-axis): 1
The plane does not return to the origin (0,0).

Output: Since the plane’s final position is (−1,1), it did not return successfully.
Result: "Not returned successfully"

Test Case 2:
Input: "NESW"
Output: "Returned successfully"
Explanation:
Move N: vertical=1.
Move E: horizontal=1.
Move S: vertical=0.
Move W: horizontal=0.
Result: Displacements are (0,0)

Test Case 3:
Input: "NNSS"
Output: "Returned successfully"
Explanation:
Move N: vertical=1.
Move N: vertical=2.
Move S: vertical=1.
Move S: vertical=0.
Result: Displacements are (0,0).

Test Case 4:
Input: "NEESWW"
Output: "Not returned successfully".
Move N: vertical=1.
Move E: horizontal=1.
Move E: horizontal=2.
Move S: vertical=0.
Move W: horizontal=1.
Move W: horizontal=0.
Result: Displacements are (0,1)

Solution: Let us break down the program

Given a string representing directions (N, S, W, E), the task is to determine whether
a jet plane returns to its starting position after following all the directions.
Each direction moves the jet by 1 unit:
N (North): Moves the plane 1 unit up.
S (South): Moves the plane 1 unit down.
E (East): Moves the plane 1 unit right.
W (West): Moves the plane 1 unit left.

Approach:
To check if the plane returns to the starting position:
1. Track the horizontal displacement and vertical displacement from the starting
position.
a. Horizontal displacement (x-axis): Affected by E and W.
b. Vertical displacement (y-axis): Affected by N and S.
2. For every character in the string:
a. Update the horizontal displacement (+1 for E, -1 for W).
b. Update the vertical displacement (+1 for N, -1 for S).
3. At the end, if both horizontal and vertical displacements are 0, the plane has
returned to its starting position.

Solution in Java
public class JetPlane
{
public static String hasReturned(String directions) {
// Initialize displacement variables
int horizontal = 0; // x-axis
int vertical = 0; // y-axis

// Iterate over each direction in the string


for (char direction : directions.toCharArray()) {
switch (direction) {
case 'N': vertical++; break; // Move North
case 'S': vertical--; break; // Move South
case 'E': horizontal++; break; // Move East
case 'W': horizontal--; break; // Move West
}
}

// Check if both displacements are zero


if (horizontal == 0 && vertical == 0) {
return "Returned successfully";
} else {
return "Not returned successfully";
}
}

public static void main(String[] args) {


// Test cases
System.out.println(hasReturned("NESW")); // Output: Returned successfully
System.out.println(hasReturned("NNSS")); // Output: Returned successfully
System.out.println(hasReturned("NEESWW")); // Output: Not returned
successfully
System.out.println(hasReturned("")); // Output: Returned successfully
System.out.println(hasReturned("NWNESW")); // Output: Not returned
successfully
}
}

Solution in Python
def has_returned(directions):
# Initialize displacement variables
horizontal = 0 # x-axis
vertical = 0 # y-axis

# Iterate over each direction in the string


for direction in directions:
if direction == 'N':
vertical += 1 # Move North
elif direction == 'S':
vertical -= 1 # Move South
elif direction == 'E':
horizontal += 1 # Move East
elif direction == 'W':
horizontal -= 1 # Move West
# Check if both displacements are zero
if horizontal == 0 and vertical == 0:
return "Returned successfully"
else:
return "Not returned successfully"

# Test cases
print(has_returned("NESW")) # Output: Returned successfully
print(has_returned("NNSS")) # Output: Returned successfully
print(has_returned("NEESWW")) # Output: Not returned successfully
print(has_returned("")) # Output: Returned successfully
print(has_returned("NWNESW")) # Output: Not returned successfully
----------------------------------------------------------------------------------------
Program 4

Description:
Alice has introduced a new online game which has N levels i e., 1 to N. She wants to
get reviews for each level of this game so she will launch only a single level of game
on any day, and on that day users of this game are allowed to play only that level.
As there are N levels so it will take exactly N days to launch all levels of the game, it
is not necessary that level of game will be launched in increasing order, she will pick
any random level on particular day and launch it, and it is obvious that any level of
the game can’t be launched twice. After completing the level, the user will give
reviews and she will give them one reward unit for each level the user will
complete. Alice has put one constraint on users that only after completing any level
of game, user will be able to play higher levels. For E.g. If Alice has launched the 3rd
level of the game on the first day and if any user completes it then he will get one
reward point, but now. he can’t play the game with level 1 and level 2.

NOTE: If a user wants to skip to play on any number of days, he is free to do that.

You are the best gamer, so you can easily complete all levels. As you want to
maximize your reward points, you want to play as many levels as you can. Alice has
already announced the order in which she will launch levels of his game, your aim is
to maximize your reward points.

Given number of levels of games(N) and order of level of games launched one by
one on each day. You have to output maximum reward points you can earn.

Hint: You will play any game if and only if that number is becoming the part of the
longest subsequence in array of order of games.

Example 1:
Input:
5 -> N = 5
2 1 3 4 5 -> Order of levels, Alice will launch one by one
Output:
4
Explanation:
If you play the 2nd level of the game on the first day, then you will not be able to
play the 1st level of the game on the 2nd day. As after completing the 2nd level,
you will be able to play higher levels. From 3rd day you can play all upcoming levels
as those levels are in increasing order. So, possible sequences of levels of games
played to maximize rewards points are [2, 3, 4, 5] or [1, 3, 4, 5]. In both cases you
will get 4 reward points.

Example 2:
Input:
5 -> N = 5
5 4 3 2 1 -> Order of levels, Alice will launch one by one
Output:
1
Explanation:
Alice has launched levels in decreasing order, so you will be able to play exactly one
level of game. After playing any level, there are no higher levels on coming days, so
maximum reward point is 1.

Solution in Java

import java.util.*;
public class AliceGame {
public static void main(String [] args){
int n,i,j,point=0;
Scanner in = new Scanner(System.in);
n=in.nextInt();
int num[]=new int[n];
int numscore[]=new int[n];
for(i=0;i<n;i++)
{
num[i] =in.nextInt();
}
in.close();
for(i=0;i<n;i++){
point=0;
for(j=i+1;j<n;j++){
if(num[i]<num[j]){
point+=1;
}
}
numscore[i]=point+1;;
}
Arrays.sort(numscore);
int max=numscore[n-1];
System.out.print(max);
}

}
----------------------------------------------------------------------------------------

You might also like