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

Accenture Coding Question

The document contains a series of coding questions and their solutions, covering various programming concepts such as reversing a number, finding the largest number in an array, and checking for prime numbers. Each question is accompanied by a code snippet in Java that demonstrates the solution. The topics range from basic algorithms to data structure manipulations, including linked lists and binary trees.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
3 views

Accenture Coding Question

The document contains a series of coding questions and their solutions, covering various programming concepts such as reversing a number, finding the largest number in an array, and checking for prime numbers. Each question is accompanied by a code snippet in Java that demonstrates the solution. The topics range from basic algorithms to data structure manipulations, including linked lists and binary trees.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 79

Accenture Coding Question

One Shot
Q.1 Reverse a number .
int number = 987654
class Main {
public static void main(String[] args) {

int num = 1234, reversed = 0;

System.out.println("Original Number: " + num);

// run loop until num becomes 0


while(num != 0) {

// get last digit from num


int digit = num % 10;
reversed = reversed * 10 + digit;

// remove the last digit from num


num /= 10;
}

System.out.println("Reversed Number: " + reversed);


}
}
Q.2 Find the largest number in an array
Int arr[] = { 1, 4, 6 ,7 ,8 , 9 }
1.public class LargestElement_array {
2. public static void main(String[] args) {
3.
4. //Initialize array
5. int [] arr = new int [] {25, 11, 7, 75, 56};
6. //Initialize max with first element of array.
7. int max = arr[0];
8. //Loop through the array
9. for (int i = 0; i < arr.length; i++) {
10. //Compare elements of array with max
11. if(arr[i] > max)
12. max = arr[i];
13. }
14. System.out.println("Largest element present in given ar
ray: " + max);
15. }
16.}
Q.3 Given an integer array nums, find the
subarray with the largest sum, and return its sum.
• Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
• Output: 6
class Solution {
public int maxSubArray(int[] nums) {
int sum=0;
int max=Integer.MIN_VALUE;
for(int i=0;i<nums.length;i++){
sum+=nums[i];
max=Math.max(max, sum);
if(sum<0){
sum=0;
}

}
return max;

}
}
Q.4 Write a code for Prime Number .
Prime number is a number that is greater than 1 and divided by 1 or
itself only.
1. public static boolean isPrime(int n) {
2. if (n <= 1) {
3. return false;
4. }
5. for (int i = 2; i <= Math.sqrt(n); i++) {
6. if (n % i == 0) {
7. return false;
8. }
9. }
10. return true;
11. }
12.}
Q.5 Find target element in an array .
• int[] array = {2, 3, 4, 10, 40};
• int target = 10;
public class BinarySearch {

public static int binarySearch(int[] array, int


target) {
int left = 0;
int right = array.length - 1;

while (left <= right) {


int mid = left + (right - left) / 2;

if (array[mid] == target) {
return mid;
}

if (array[mid] < target) {


left = mid + 1;
} else {
right = mid - 1;
}
}

return -1;
}
Q.6 Find the middle of linkedlist
class Solution {
public ListNode middleNode(ListNode head) {
ListNode slow=head,fast=head;
while(fast!=null && fast.next!=null){
slow=slow.next;
fast=fast.next.next;
}
return slow;
}

}
Q.7 Given head, the head of a linked list, determine
if the linked list has a cycle in it.
public class Solution {
public boolean hasCycle(ListNode head) {
ListNode slow= head, fast=head;
while(fast != null && fast.next !=null ){
slow =slow.next;
fast=fast.next.next;
if(slow==fast)
return true;
}
return false;

}
}
Q.8 Given two strings s and t, return true if t is
an anagram of s, and false otherwise.
An Anagram is a word or phrase formed by rearranging the letters of a
different word or phrase, typically using all the original letters exactly
once.
Input: s = "anagram", t = "nagaram"
Output: true
class Solution {
public boolean isAnagram(String s, String t) {
if(s.length()!=t.length()){
return false;
}
int map[]=new int[26];
for(int i=0;i<s.length();i++){
map[s.charAt(i)-'a']++;
map[t.charAt(i)-'a']--;
}

for(int i=0;i<26;i++){
if(map[i]!=0){
return false;
}
}
return true;
}
}
Q.9 Find the missing number in an array .
Given an array nums containing n distinct numbers in the range [0, n],
return the only number in the range that is missing from the array.
Input: nums = [3,0,1]
Output: 2
class Solution {
public int missingNumber(int[] nums) {
int n=nums.length;
int total=(n)*(n+1)/2;
int sum=0;
for(int i=0;i<nums.length;i++){
sum+=nums[i];
}
return total-sum;
}
}
Q.10 The function accepts a string ‘str’ as its argument. The
function needs to return the transformed string by replacing all
occurrences of the character ‘a’ with the character ‘b’ and vice
versa.

Input :- abaabbcc
public class StringTransformation {
public static String transformString(String str) {
char[] charArray = str.toCharArray();
for (int i = 0; i < charArray.length; i++) {
if (charArray[i] == 'a')
charArray[i] = 'b';
else if (charArray[i] == 'b')
charArray[i] = 'a';
}
return new String(charArray);
}
public static void main(String[] args) {
String str = "abaabbcc";
System.out.println(transformString(str));
}
Q.11 Check whether string is palindrome or
not.
public static boolean isPalindrome(String str) {
int left = 0;
int right = str.length() - 1;
while (left < right) {
if (str.charAt(left) != str.charAt(right)) {
return false; // Not a palindrome
}
left++;
right--;
}
return true;
}
Q.12 The function accepts a string ‘str’ as its
argument. The function needs to reverse the order
of the words in the string.
Input :- String str = "Hello, World!";
public class ReverseWords {
public static void reverseWords(String str) {
String[] words = str.split(" ");
for (int i = words.length - 1; i >= 0; i--) {
System.out.print(words[i] + " ");
}
}
public static void main(String[] args) {
String str = "Hello, World!";
reverseWords(str);
}
}
Q.13 Count the Occurrences of a Given
Element in an Array.
• int[] arr = {5, 2, 4, 1, 2};
• int element = 2;
public class OccurrenceCounter {
public static int countOccurrences(int[] arr, int element) {
int count = 0;
for (int num : arr) {
if (num == element) {
count++;
}
}
return count;
}
public static void main(String[] args) {
int[] arr = {5, 2, 4, 1, 2};
int element = 2;
int result = countOccurrences(arr, element);
System.out.println(result);
}
}
Q.14 Calculate and return the difference between the sum of
square roots of even numbers and the sum of square roots of
odd numbers in the range from ‘m’ to ‘n’ (inclusive).

Input :- int m = 1, n = 10;


public class SquareRootDifference {
public static double squareRootDifference(int m, int n) {
double evenSum = 0, oddSum = 0;
for (int i = m; i <= n; ++i) {
double squareRoot = Math.sqrt(i);
if (i % 2 == 0) {
evenSum += squareRoot;
} else {
oddSum += squareRoot;
}
}
return evenSum - oddSum;
}
public static void main(String[] args) {
int m = 1, n = 10;
double result = squareRootDifference(m, n);
System.out.printf("%.5f\n", result);
}
}
Q.15 Search a 2D Matrix
Input: matrix = [[1,3,5,7],[10,11,16,20],[23,30,34,60]], target = 3
Output: true
class Solution {
public boolean searchMatrix(int[][] matrix, int target) {
int row= matrix.length;
int col= matrix[0].length;

int low=0, high=row*col-1;


while(low<=high){
int mid=(low+high)/2;
if(matrix[mid/col][mid%col]== target){
return true;
}
else if(matrix[mid/col][mid%col]<target){
low=mid+1;
}
else{
high=mid-1;
}
}
return false;

}
Q.16 Check If Two String Arrays are Equivalent
Input: word1 = ["ab", "c"], word2 = ["a", "bc"]
class Solution {
public boolean arrayStringsAreEqual(String[] word1, String[] word2) {
StringBuilder string1 =new StringBuilder();
StringBuilder string2 =new StringBuilder();
for(int i=0;i<word1.length;i++){
string1.append(word1[i]);

}
for(int i=0;i<word2.length;i++){
string2.append(word2[i]);
}
if(string1.toString().equals(string2.toString()))
return true;
else
return false;
}
}
Q.17 Inorder Traversal
public class BinaryTreeInorderTraversal {

public static void inorder(Node root, List<Integer> arr) {

if (root == null) {
return;
}
// Recursively traverse the left subtree
inorder(root.left, arr);
arr.add(root.data);
inorder(root.right, arr);
}
Q.18 Preorder Traversal
public class BinaryTreeTraversal {

static void preorder(Node root, List<Integer> arr) {

if (root == null) {
return;
}
arr.add(root.data);
preorder(root.left, arr);
preorder(root.right, arr);
}
Q.19 Post Order Traversal
public class BinaryTreeTraversal {
static void postorder(Node root, List<Integer> arr){

if(root == null){
return;
}
postorder(root.left, arr);
postorder(root.right, arr);
arr.add(root.data);
}
Q.20 Best Time to Buy and Sell Stock
You want to maximize your profit by choosing a single day to buy one
stock and choosing a different day in the future to sell that stock.

Input: prices = [7,1,5,3,6,4]


Output : 5
class Solution {
public int maxProfit(int[] prices) {
int min=Integer.MAX_VALUE;
int max=Integer.MIN_VALUE;
for(int i=0;i<prices.length;i++){
min=Math.min(min,prices[i]);
max=Math.max(max,prices[i]-min);
}
return max;
}
}
Q.21 The Fibonacci numbers, commonly denoted F(n) form a
sequence, called the Fibonacci sequence, such that each
number is the sum of the two preceding ones, starting from 0
and 1.
• Input: n = 2
• Output: 1
class Solution {
public int fib(int n) {
if(n<=1){
return n;
}
return fib(n-1)+fib(n-2);

}
}
Q.22 Given an array, we have found the number of
occurrences of each element in the array.
Input: arr[] = {10,5,10,15,10,5};
public class ElementFrequency {
public static void main(String[] args) {
int[] array = {1, 2, 2, 3, 4, 4, 4, 5};

HashMap<Integer, Integer> frequencyMap = new HashMap<>();

for (int element : array) {


if (frequencyMap.containsKey(element)) {
frequencyMap.put(element, frequencyMap.get(element) + 1);
}
else {
frequencyMap.put(element, 1);
}
}

for (int key : frequencyMap.keySet()) {

System.out.println("Element: " + key + " - Frequency: " + frequencyMap.get(key)); } }}


Q.23 Rearrange Array Elements by Sign.

You are given a 0-indexed integer array nums of even length consisting
of an equal number of positive and negative integers.

Input: nums = [3,1,-2,-5,2,-4]


Output: [3,-2,1,-5,2,-4]
class Solution {
public int[] rearrangeArray(int[] nums) {
ArrayList<Integer> positive=new ArrayList<>();
ArrayList<Integer> negative=new ArrayList<>();
for(int i=0;i<nums.length;i++){
if(nums[i]>0){
positive.add(nums[i]);
}
}
for(int i=0;i<nums.length;i++){
if(nums[i]<0){
negative.add(nums[i]); }}
int arr[]=new int[nums.length];
int k=0;
int c=0;
while(c<positive.size()){

arr[k]=positive.get(c);
arr[k+1]=negative.get(c);
k+=2;
c++;

}
return arr;
Q.24 Write a Program to Find if a Given Year is
a Leap Year.
#include<bits/stdc++.h>

using namespace std;

int main() {
int year;

cout << "Enter Year:" << endl;


cin >> year;

if (year % 400 == 0)
cout << year << " is a Leap Year";

else if (year % 4 == 0 && year % 100 != 0)


cout << year << " is a Leap Year";

else
cout << year << " is not a Leap Year";

return 0;
}
Q.25 Write a program for factorial of number.
Input N=5 ;
public static long factorialIterative(int n)
{
long result = 1;

for (int i = 1; i <= n; i++) {


result *= i;
}
return result; }
}
Q.26 write a code in java find the sum of the
divisor of N integer

Input : N=48;
public static int sumOfDivisors(int n) {
int sum = 0;
for (int i = 1; i <= n; i++) {
if (n % i == 0) {
sum += i;
}
}
return sum;
}
Q.27 Merge Sorted Array
• Input: nums1 = [1,2,3,0,0,0], m = 3, nums2 = [2,5,6], n = 3
• Output: [1,2,2,3,5,6]
class Solution {
public void merge(int[] nums1, int m, int[] nums2, int n) {
int i=0,j=0,k=0;
int arr[]=new int [m+n];
while(i<m && j<n){
if(nums1[i]<nums2[j]){
arr[k++]=nums1[i++];
}
else{
arr[k++]=nums2[j++];
}
}
while(i<m){
arr[k++]=nums1[i++];
}
while(j<n){
arr[k++]=nums2[j++];
}
for(int c=0;c<arr.length;c++){
nums1[c]=arr[c];
}

}
}
Q.28 Write a program to find the sum of Natural
Numbers using Recursion
Input :N=10
public class Main
{
public static void main (String[]args)
{

int n = 10;
int sum = getSum (n);

System.out.println (sum);
}

static int getSum (int n)


{
if (n == 0)
return n;

return n + getSum (n - 1);


}
}

You might also like