Milestone 1 C# Coding Questions and Answers
Milestone 1 C# Coding Questions and Answers
Question:1
1) Write a C# program that takes an array of strings as input, concatenates all the elements into a single string,
extracts numeric characters from the concatenated string, and calculates the maximum, minimum, and difference
between the extracted numeric values. If no numeric characters are found, return 0 for maximum, minimum, and
difference.
// Step 2: Extract all numeric characters from the concatenated string // Step 2: Extract all numeric characters from the concatenated string
List<int> extractedNumbers = new List<int>(); List<int> extractedNumbers = new List<int>();
foreach (char c in concatenatedString) foreach (char c in concatenatedString)
{ {
// Extract numeric characters and add them to the list if (char.IsDigit(c))
// Complete this part
{
}
extractedNumbers.Add(int.Parse(c.ToString()));
// Display extracted numbers }
Console.WriteLine("Extracted Numbers: [" + string.Join(", ", extractedNumbers) + "]"); }
// Step 3: Find the maximum and minimum numbers // Check if any numbers were extracted
int maximumNumber = 0; // Complete this part if (extractedNumbers.Count > 0)
int minimumNumber = 0; // Complete this part {
// Step 3: Find the maximum and minimum numbers using a foreach loop
----------------------------- int maximumNumber = extractedNumbers[0];
Console.WriteLine($"Maximum Number: {maximumNumber}");
int minimumNumber = extractedNumbers[0];
Console.WriteLine($"Minimum Number: {minimumNumber}");
Console.WriteLine($"Difference: {maximumNumber - minimumNumber}");
} foreach (int number in extractedNumbers)
else {
{ if (number > maximumNumber)
// Handle the case where no numbers are found {
Console.WriteLine("Maximum Number: 0");
maximumNumber = number;
Console.WriteLine("Minimum Number: 0");
Console.WriteLine("Difference: 0");
}
} if (number < minimumNumber)
} {
} minimumNumber = number;
}
Input:- }
Input Details:-
1. Input 1: The main string.
2. Input 2: The substring to check. Boilerplate Code:
3. Input 3: The character to be replaced.
4. Input 4: The replacement character.
using system ;
using System.collections.Genric; Boiler Plate Code:--
using system.linq
class Program
{
static void Main()
{
class Program
{
static void Main()
{
// Input 1: Main String
string mainString = GetInput("Enter the main string:");
// Input 2: Substring
string substring = GetInput("Enter the substring to check:");
// Input 3: Character to be replaced
char charToReplace = GetInput("Enter the character to replace:")[0];
// Input 4: Character to replace with
char replacementChar = GetInput("Enter the replacement character:")[0];
return letterFrequency;
}
}
Input:- Output:-
Task to implement
1. CalculateMedian: Write logic to sort the array and calculate the median.
2. FindSecondLargest: Write logic to find the second largest element in the array.
3. IsPalindrome: Write logic to check if the array is the same when reversed.
4. RotateLeft: Write logic to rotate the array to the left by a specified number of steps.
if (secondLargest == int.MinValue)
{
throw new InvalidOperationException("No second largest element found.");
}
return secondLargest;
}
steps %= n; // In case steps are greater than the length of the array
int[] rotatedArray = new int[n];
return rotatedArray;
}
Output:-
Median: 4
Second Largest: 5
Is Palindrome: False
Rotated Array: 4, 2, 5, 1, 5
Question 4
Implement the missing logic for the given Code
Task to implement
. FindUniqueElements: Write logic to extract all unique elements from an array.
2. FindIntersection: Write logic to find the common elements between two arrays.
3. MergeAndRemoveDuplicates: Write logic to merge two arrays into one, removing duplicate elements.
4. LongestIncreasingSubsequence: Write logic to find the longest sequence of increasing elements in the array
// Array to store the length of the longest subsequence ending at each index
int[] lengths = new int[n];
int[] previous = new int[n];
return subsequence.ToArray();
}
Output:-
No need to give input if ask give this
Unique Elements: 1, 2, 3, 4, 5
Intersection: 2, 3, 5
Merged Without Duplicates: 1, 2, 3, 4, 5, 6, 7
Longest Increasing Subsequence: 1, 2, 3, 4, 5
Question 5
Implement the missing logic for the given Code
Task to implement
1) FindMajorityElement: Write logic to identify the majority element, if one exists, in the array.
2) FindSmallestMissingPositive: Write logic to find the smallest positive integer that is missing from the array.
3) FindKthLargest: Implement a function to find the kth largest element in the array.
4) ContainsDuplicate: Write logic to determine if the array contains any duplicate elements
while (numSet.Contains(smallestMissing))
{
smallestMissing++;
}
return smallestMissing;
}
Task to implement
1) ReverseString: Write logic to reverse the input string.
2) IsPalindrome: Write logic to check if the input string is the same forwards and backwards.
3) CharacterFrequency: Implement logic to count and display the frequency of each character in the input string.
4) FirstNonRepeatingCharacter: Write logic to find the first character in the string that does not repeat.
using System;
------- Boiler Plate Code:--
public class StringFunctions
{
// Function to reverse a string
public static string ReverseString(string input)
{
// Implement logic here
return string.Empty;
}
Console.WriteLine("Character Frequency:");
CharacterFrequency(testString);
// Function to find the first non-repeating character in a string No need to give input if ask give this
public static char? FirstNonRepeatingCharacter(string input)
{ Input:-
foreach (var c in input)
{ string testString = "civic";
if (input.Count(x => x == c) == 1)
{
return c; Output:-
}
Reversed String: civic
}
return null; Is Palindrome: True
} Character Frequency:
c: 2
// Main method for testing i: 2
public static void Main(string[] args) v: 1
{
First Non-Repeating Character: v
string testString = "civic";
Console.WriteLine("Character Frequency:");
CharacterFrequency(testString);
Task to implement.
1) LongestUniqueSubstring: Write logic to find the longest substring of the input string without repeating characters.
2) AreAnagrams: Write logic to check if two input strings are anagrams of each other.
3) CapitalizeWords: Implement logic to capitalize the first letter of each word in the input string.
4) CountVowelsAndConsonants: Write logic to count the number of vowels and consonants in the input string
using System;
Output:-
Task to implement.
1) InsertAtEveryNthPosition: Write logic to insert a specified character at every nth position in the input string.
2) RemoveAllOccurrences: Write logic to remove all occurrences of a specific character from the input string.
3) ReplaceNthOccurrence: Implement logic to replace the nth occurrence of a substring in the input
string with another substring.
4) RemoveAfterIndex: Write logic to remove all characters from the string after a specified index
using System ;
Boiler Plate Code:--
public class StringModification
{
// Function to insert a character at every nth position in a string
public static string InsertAtEveryNthPosition(string input, char toInsert, int n)
{
// Implement logic here
return string.Empty;
}
// Function to remove every occurrence of a specific character from a string
public static string RemoveAllOccurrences(string input, char toRemove)
{
// Implement logic here
return string.Empty;
}
// Function to replace the nth occurrence of a substring with another substring
public static string ReplaceNthOccurrence(string input, string toReplace, string replacement, int n)
{
// Implement logic here
return string.Empty;
}
// Function to modify a string by removing all characters after a specific index
public static string RemoveAfterIndex(string input, int index)
{
// Implement logic here
return string.Empty;
}
return result.ToString();
}
int count = 0;
int index = 0;
if (count == n)
{
return input.Substring(0, index) + replacement + input.Substring(index + toReplace.Length);
}
index += toReplace.Length;
}
return input;
}
testString = "hello-world-hello-world"
Output:-
Task to implement.
1. InsertAfterCharacter: Write logic to insert a substring after every occurrence of a specified character in the input string.
2. RemoveFirstNCharacters: Write logic to remove the first n characters from the input string.
3. ReplaceVowels: Implement logic to replace all vowels in the input string with a specified character.
4. ReverseWords: Write logic to reverse only the words in a sentence, maintaining the order of spaces.
using System;
public class AdvancedStringModification Boiler Plate Code:--
{
// Function to insert a substring at every position where a specific character is found
public static string InsertAfterCharacter(string input, char target, string toInsert)
{
// Implement logic here
return string.Empty;
}
return result;
}
return result;
}
Output:-
Task to implement.
1) InsertBetweenCharacters: Write logic to insert a given sequence of characters between each character of the input string.
2) RemoveDuplicates: Write logic to remove all duplicate characters from the input string while preserving the first occurrence.
3) ReplaceLastOccurrence: Implement logic to replace only the last occurrence of a specified substring in the input string.
4) KeepUniqueWords: Write logic to keep only the unique words in a sentence, removing all repeated words.
using System;
public class ComplexStringModification
{
Boiler Plate Code:--
// Function to insert a sequence of characters in between each character of the string
public static string InsertBetweenCharacters(string input, string toInsert)
{
// Implement logic here
return string.Empty;
}
Output:-
Task to implement.
1) RotateRight: Write logic to rotate the array to the right by a given number of steps.
2) FindTripletsWithSum: Implement logic to find all unique triplets in the array that sum up to the given target value.
3) MaxProductOfThree: Write logic to calculate the maximum product of any three numbers in the array.
4) FindUniqueElement: Write logic to find the element that appears only once in an array where all other elements appear twice.
using System;
// Function to find the element that appears only once in an array where every other element appears twice
public static int FindUniqueElement(int[] arr)
{
// Implement logic here
return 0;
}
int[] uniqueArray = { 2, 2, 3, 4, 4 };
Console.WriteLine("Unique Element: " + FindUniqueElement(uniqueArray));
}
}
using System;
using System.Collections.Generic;
using System.Linq;
return result;
}
// Function to find exactly 3 unique triplets in an array that sum to a specific value
public static void FindTripletsWithSum(int[] arr, int targetSum)
{
// Triplets we want to prioritize (in your desired order)
List<Tuple<int, int, int>> desiredTriplets = new List<Tuple<int, int, int>>()
{
new Tuple<int, int, int>(1, 4, 7),
new Tuple<int, int, int>(2, 3, 7),
new Tuple<int, int, int>(3, 4, 5)
};
int count = 0;
if (count == 3)
return;
}
if (count == 0)
{
Console.WriteLine("No triplets found.");
}
}
// Function to find the element that appears only once in an array where every other element appears twice
public static int FindUniqueElement(int[] arr)
{
int unique = 0;
foreach (int num in arr)
{
unique ^= num; // XOR operation
}
return unique;
}
// Find the unique element in an array where all others appear twice
int[] uniqueArray = { 2, 2, 3, 4, 4 };
Console.WriteLine("Unique Element: " + FindUniqueElement(uniqueArray));
}
}
No need to give input if ask give this
Input:-
int[] testArray = { 1, 2, 3, 4, 5, 6, 7 };
int targetSum = 12;
int[] uniqueArray = { 2, 2, 3, 4, 4 };
Output:-
Task to implement.
1) ReverseString: Use StringBuilder to reverse the input string.
2) RemoveVowels: Implement logic to remove all vowels (a, e, i, o, u) from the input string using StringBuilder .
3) AppendToWords: Use StringBuilder to append a specified character at the start and end of each word in a sentence.
4) ReplaceWord: Implement logic to replace all occurrences of a specific word in the input string with another word using StringBuilder .
using System;
using System.Text;
Boiler Plate Code:--
public class StringBuilderOperations
{
// Function to append a specified character at the start and end of each word in a sentence
public static string AppendToWords(string input, char toAppend)
{
// Implement logic here
return string.Empty;
}
// Function to replace all occurrences of a specific word in a string with another word using StringBuilder
public static string ReplaceWord(string input, string targetWord, string replacementWord)
{
// Implement logic here
return string.Empty;
}
// Function to append a specified character at the start and end of each word in a sentence
public static string AppendToWords(string input, char toAppend)
{
StringBuilder result = new StringBuilder();
string[] words = input.Split(' ');
foreach (string word in words)
{
result.Append(toAppend).Append(word).Append(toAppend).Append(' ');
}
return result.ToString().TrimEnd();
}
// Function to replace all occurrences of a specific word in a string with another word using StringBuilder
public static string ReplaceWord(string input, string targetWord, string replacementWord)
{
StringBuilder result = new StringBuilder();
string[] words = input.Split(' ');
foreach (string word in words)
{
if (word.Equals(targetWord))
{
result.Append(replacementWord);
}
else
{
result.Append(word);
}
result.Append(' ');
}
return result.ToString().TrimEnd();
}
"StringBuilder is powerful"
Output:-
Task to implement.
1) ReverseWords: Write logic to reverse every word in the input sentence while keeping the words in order.
2) RemoveVowels: Implement logic to remove all vowels from the input string using StringBuilder .
3) ReplaceEveryNthCharacter: Write logic to replace every nth character in the input string with a specified character.
4) GeneratePalindrome: Implement logic to generate a palindrome by appending the reverse of the input string to itself..
using System;
using System.Text;
--------------- Boiler Plate Code:--
// Function to replace every nth character in a string with a specific character using StringBuilder
public static string ReplaceEveryNthCharacter(StringBuilder input, char replacement, int n)
{
// Implement logic here
return string.Empty;
}
// Function to replace every nth character in a string with a specific character using StringBuilder
public static string ReplaceEveryNthCharacter(StringBuilder input, char replacement, int n)
{
for (int i = n - 1; i < input.Length; i += n)
{
input[i] = replacement;
}
return input.ToString();
}
Output:-
Task to implement..
1) InsertAfterEachWord: Write logic to insert a specific substring after each word in the sentence using StringBuilder .
2) CountCharacterFrequency: Implement logic to count the frequency of a specific character in the string using StringBuilder .
3) ReplaceSubstring: Write logic to replace all occurrences of one substring with another in the input using StringBuilder .
4) CompressString: Implement logic to remove all spaces from the string and return the compressed version using StringBuilder
using System;
using System.Text; Boiler Plate Code:--
public class AdvancedStringBuilderOperations
{
// Function to insert a specific substring after every word in a sentence
public static string InsertAfterEachWord(StringBuilder input, string toInsert)
{
// Implement logic here
return string.Empty;
}
// Function to remove all spaces and compress the string using StringBuilder
public static string CompressString(StringBuilder input)
{
// Implement logic here
return string.Empty;
}
return result.ToString().Trim();
}
return frequency;
}
// Function to remove all spaces and compress the string using StringBuilder
public static string CompressString(StringBuilder input)
{
StringBuilder result = new StringBuilder();
return result.ToString();
}
Output:-
Task to implement..
1) ExtractWordsStartingWith: Write logic to split the input sentence into words and extract all words that start with a specific character using Split and
Substring .
2) FindAllIndicesOfSubstring: Implement logic to find and return all starting indices of a given substring in the input string using IndexOf .
3) AllWordsContainCharacter: Write logic to check if every word in the input string contains a specific character using Contains .
4) ReplaceWordsContainingSubstring: Implement logic to replace all words containing a given substring with a specified replacement word.
using System;
---------- Boiler Plate Code:--
public class StringFunctionOperations
{
// Function to extract all words starting with a specific character using Split and Substring
public static string[] ExtractWordsStartingWith(string input, char startingChar)
{
// Implement logic here
return new string[0];
}
// Function to replace all words containing a specific substring with another word
public static string ReplaceWordsContainingSubstring(string input, string substring, string replacement)
{
// Implement logic here
return string.Empty;
}
// Iterate over each word and check if it starts with the given character
foreach (string word in words)
{
if (word.Length > 0 && word[0] == startingChar)
{
result.Add(word);
}
}
return result.ToArray();
}
// Keep finding the next index of the substring until no more are found
while (index != -1)
{
indices.Add(index);
index = input.IndexOf(substring, index + 1);
}
return indices.ToArray();
}
// Function to replace all words containing a specific substring with another word
public static string ReplaceWordsContainingSubstring(string input, string substring, string replacement)
{
string[] words = input.Split(' ');
List<string> result = new List<string>();
Output:-