# General Programming Questions

## Conceptual Questions:

## 1. What is a data structure?

**A data structure is a storage format that defines the way data is stored, organized and manipulated**

Examples:

* Array
* Trees
* Graphs

## 2. What is an Array?

* An array is a collection of items stored at contiguous memory locations
* Items stored are the same type&#x20;

## 3. What is a Linked List?

**A linked list, like an array, is linear data structured in which the elements are not necessary stored in a contiguous manner**&#x20;

* It is basically a sequence of nodes, each node points towards the next node forming a chain-like structure

## 4. What is a Stack?

**Stack is a linear data structure that performs operations in a LIFO (Last in first out) order**

* In a stack, elements can only be accessed starting from the topmost to the bottom element

## 5. What is LIFO?

**LIFO stands for Last in First Out**&#x20;

It is a way of accessing, storing and retrieving data

## 6. What is a Queue?

**A Queue is a linear data structure that performs operations in a FIFO (First in first Out) order**&#x20;

## 7. What is FIFO?

**FIFO stands for First In First Out**&#x20;

* It's a way of accessing, storing and retrieving data
* The data that was stored first is extracted first

## 8. What are binary trees?

**Binary trees are an extension of the linked list structured**&#x20;

* Binary tree has two nodes at all times, a left node and a right node

## 9. What is Recursion?

**Recursion refers to a function calling itself based on a terminating condition**&#x20;

It uses LIFO and therefor makes use of the stack data structure

## 10. What is the OOPs concept?

**Stands for Object Oriented Programming System which is a paradigm that provides concepts such as objects, classes, inheritance, among others**

## 11. What are the concepts introduced in OOPs?

The concepts introduce in OOPs are:

* **Object:** A real-world entity having a particular state and behavior. It can be defined as an instance of a class
* **Class:** A logical entity that defines the blueprint from which an object can be created or instantiated
* **Inheritance:** A concept that refers to an object acquiring all the properties and behavior of a parent object. It provides code re-usability&#x20;
* **Polymorphism:** A concept that allows a task to be performed in different ways. *In Java, we use method overloading and method overriding to achive polymorphism*
* **Abstraction:** A concept that hides the internal details of an application and only shows the functionality. *In Java, we use abstract class and interface to achive abstraction*
* **Encapsulation:** A concept that refers t the wrapping of code and data together into a single unit

## 12. Explain Binary Search Tree?

**A binary search tree stores data in such a way that it can be retrieved very efficiently**&#x20;

* The left subtree contains nodes whose keys are less or equal than the node's key value
* The right subtree contains nodes whose keys are greater than the node's key value

## 13. Explain Doubly Linked Lists?

**Doubly linked lists are a special type of linked list in which traversal across the data elements can be done in both directions**&#x20;

* This is made possible by having two links in every node, one that links to the next node and another that connects to the previous node

## 14. What is a Graph?

**A graph is one type of data structure that contains a set of ordered pairs**&#x20;

* These ordered pairs are also referred to as edges or arcs and are used to connect nodes where data can be stored and retrieved

## 15. Differentiate between linear and non-linear data structure?

## 16. What is a deque?

**Is a double-ended queue**

* This is a structure in which elements can be inserted or removed from either end:&#x20;

## 17. What is the difference between Stack and Array?

## 18. What sorting algorithm is the best?

**There are many types of sorting algorithms:**

* quick sort
* bubble sort
* balloon sort
* radix sort
* merge sort
* etc...

**No algorithm can be considered as the best or fastest because each is designed for a specific type of data structure where it performs the best**

## 19. How does variable declaration affect memory?

**The amount of memory to be allocated or reserved depends on the data type being stored in that variable**

Example: A variable is declared to be INTEGER type then 32 bits of memory storage will be reserved for that variable.

## 20. What are dynamic data structures?

**Dynamic data structures are structures that expand and contract as a program runs**

* It provides a flexible means of manipulating data because it can adjust according to the size of the data

## Programming Interview Questions:

## 1. How do you reserve a string in Java?

## 2. How do you determine if a string is palidrome?

**Reverse the string and compare it to the original string. If they are equal then it is palidrome**

## 3. Find the number of occurances of a character in a string?

Java:&#x20;

1. Define a count as INT
2. Define search word
3. for loop through each character
4. in loop if character = search character then count = count + 1
5. print count

Python:

```python
count = 0
for words in wird_dict.key():
	count = int(count) + 1
print count
```

## 4. Find if the given two strings are anagrams or not?

**Two strings are anagrams if they contain a similar group of characters in a carried sequence**

Python:

```python
# function to check if two strings are anagrams or not
def check(s1, s2):
	# the sorted strings are checked
	if(sorted(s1) == sorted(s2)):
		print("The strings are anagrams")
	else:
		print("The strings are not anagrams")

# deliver code
s1 = "listen"
s2 = "silent"
check(s1, s2)
```

## 5. How do you calculate the number of vowels and consonants in a String?

Python:

```python
original = raw_input('Enter a word: ')
word = original.lower()
first = word[0]

if len(original) > 0 and original.isalpha():
	if first == "a" or "e" or "i" or "u":
		print "vowel"
	else:
		print "consonant"
else:
	print "empty"
```

## 6. How do you get the matching elements in an integer array?

Java:&#x20;

1. Define an INT array
2. Nest couple of loops where you compare the numbers against all other numbers
3. if condition to print if it does find 2 numbers matching

## 7. Code the Bubble Sort algorithm?

Java:&#x20;

1. Declare array
2. Nest couple of loops to compare the numbers
3. Then sort the array will be sorted in the ascending order if found in any other order

Python:

```python
# Python program for implementation of Bubble Sort
def bubbleSort(arr):
    n = len(arr)
  
    # Traverse through all array elements
    for i in range(n-1):
    # range(n) also work but outer loop will repeat one time more than needed.
  
        # Last i elements are already in place
        for j in range(0, n-i-1):
  
            # traverse the array from 0 to n-i-1
            # Swap if the element found is greater
            # than the next element
            if arr[j] > arr[j + 1] :
                arr[j], arr[j + 1] = arr[j + 1], arr[j]
  
# Driver code to test above
arr = [64, 34, 25, 12, 22, 11, 90]
  
bubbleSort(arr)
  
print ("Sorted array is:")
for i in range(len(arr)):
    print ("% d" % arr[i]), 
```

## 8. Code the Insertion Sort algorithm?

Python:

```python
# Python program for implementation of Insertion Sort

# Function to do insertion sort
def insertionSort(arr):
  
    # Traverse through 1 to len(arr)
    for i in range(1, len(arr)):
  
        key = arr[i]
  
        # Move elements of arr[0..i-1], that are
        # greater than key, to one position ahead
        # of their current position
        j = i-1
        while j >=0 and key < arr[j] :
                arr[j+1] = arr[j]
                j -= 1
        arr[j+1] = key
  
  
# Driver code to test above
arr = [12, 11, 13, 5, 6]
insertionSort(arr)
print ("Sorted array is:")
for i in range(len(arr)):
    print ("%d" %arr[i])
```

## 9. How to reverse an array?

Python:

Using List Slicing to Reverse an Array in Python:

```python
#The original array
arr = [11, 22, 33, 44, 55]
print("Array is :",arr)
 
res = arr[::-1] #reversing using list slicing
print("Resultant new reversed array:",res)
```

Output:

```
Array is : [1, 2, 3, 4, 5]
Resultant new reversed array: [5, 4, 3, 2, 1]
```

Using reverse() Method

```python
#The original array
arr = [11, 22, 33, 44, 55]
print("Before reversal Array is :",arr)
 
arr.reverse() #reversing using reverse()
print("After reversing Array:",arr)
```

Output:

```
Before reversal Array is : [11, 22, 33, 44, 55]
After reversing Array: [55, 44, 33, 22, 11]
```

## 10. Swap two numbers without using a third variable

```python
a = 10
b = 20

b = b + a
a = b - a
b = b - a
```

## 11. Print a Fibonacci series using recurison?

```python
# Python program to display the Fibonacci sequence
def recur_fibo(n):
	if n <= 1:
      	return n
	else:
      	return(recur_fibo(n-1) + recur_fibo(n-2))

nterms = 10

# check if the number of terms is valid
if nterms <= 0:
  	print("Plese enter a positive integer")
else:
  	print("Fibonacci sequence:")
   	for i in range(nterms):
    	print(recur_fibo(i))
```

## 12. How do you find the factorial of a number?

```python
# Python program to find the factorial of a number provided by the user.

# change the value for a different result
num = 7

# To take input from the user
#num = int(input("Enter a number: "))

factorial = 1

# check if the number is negative, positive or zero
if num < 0:
  	print("Sorry, factorial does not exist for negative numbers")
elif num == 0:
   	print("The factorial of 0 is 1")
else:
   	for i in range(1,num + 1):
      	factorial = factorial*i
   	print("The factorial of",num,"is",factorial)
```

## 13. Reverse a linked list?

```python
# Python program to reverse a linked list
# Time Complexity : O(n)
# Space Complexity : O(n) as 'next'
#variable is getting created in each loop.
 
# Node class
 
 
class Node:
 
    # Constructor to initialize the node object
    def __init__(self, data):
        self.data = data
        self.next = None
 
 
class LinkedList:
 
    # Function to initialize head
    def __init__(self):
        self.head = None
 
    # Function to reverse the linked list
    def reverse(self):
        prev = None
        current = self.head
        while(current is not None):
            next = current.next
            current.next = prev
            prev = current
            current = next
        self.head = prev
 
    # Function to insert a new node at the beginning
    def push(self, new_data):
        new_node = Node(new_data)
        new_node.next = self.head
        self.head = new_node
 
    # Utility function to print the linked LinkedList
    def printList(self):
        temp = self.head
        while(temp):
            print temp.data,
            temp = temp.next
 
 
# Driver program to test above functions
llist = LinkedList()
llist.push(20)
llist.push(4)
llist.push(15)
llist.push(85)
 
print "Given Linked List"
llist.printList()
llist.reverse()
print "\nReversed Linked List"
llist.printList()
```

## 14. How do you implement Binary Search?

```python
# Python 3 program for recursive binary search.
# Modifications needed for the older Python 2 are found in comments.
 
# Returns index of x in arr if present, else -1
def binary_search(arr, low, high, x):
 
    # Check base case
    if high >= low:
 
        mid = (high + low) // 2
 
        # If element is present at the middle itself
        if arr[mid] == x:
            return mid
 
        # If element is smaller than mid, then it can only
        # be present in left subarray
        elif arr[mid] > x:
            return binary_search(arr, low, mid - 1, x)
 
        # Else the element can only be present in right subarray
        else:
            return binary_search(arr, mid + 1, high, x)
 
    else:
        # Element is not present in the array
        return -1
 
# Test array
arr = [ 2, 3, 4, 10, 40 ]
x = 10
 
# Function call
result = binary_search(arr, 0, len(arr)-1, x)
 
if result != -1:
    print("Element is present at index", str(result))
else:
    print("Element is not present in array")
```

## 15. Find the second largest number in an array?

```python
import array
arr = []
n = int(input("enter size of array : "))
for x in range(n):
    x=int(input("enter element of array : "))
    arr.append(x)
 
sorted_array = sorted(array.array('i', arr))
for i in range(len(arr)-1, 0, -1):
    if sorted_array[i]!=sorted_array[i-1]:
        print(f"second largest element is {sorted_array[i-1]}")
        break 
```

## 16. How do you remove all occurances of a given character from the input string?

```python
a = "Australia"
a = a.replace("a", "");
print a
```

## 17. Showcase Inheritance with the help of a program?

```python
class Polygon:
    def __init__(self, no_of_sides):
        self.n = no_of_sides
        self.sides = [0 for i in range(no_of_sides)]

    def inputSides(self):
        self.sides = [float(input("Enter side "+str(i+1)+" : ")) for i in range(self.n)]

    def dispSides(self):
        for i in range(self.n):
            print("Side",i+1,"is",self.sides[i])
```

## 18. Explain overloading and overriding with the help of a program?

**Overloading**: When a class has two or more methods with the same name they are called overloaded methods&#x20;

**Overriding:** When a superclass method is also implemented in the child class, it's a case of overriding&#x20;

## 19. Check if the given number is prime?

```python
# Program to check if a number is prime or not

num = 29

# To take input from the user
#num = int(input("Enter a number: "))

# define a flag variable
flag = False

# prime numbers are greater than 1
if num > 1:
    # check for factors
    for i in range(2, num):
        if (num % i) == 0:
            # if factor is found, set flag to True
            flag = True
            # break out of loop
            break

# check if flag is True
if flag:
    print(num, "is not a prime number")
else:
    print(num, "is a prime number")
```

## 20. Sum up all elements in an array

```python
# Python program for sum of the array elements

# functions to find sum of elements

# Approach 1
def sum_1(arr):
    result = 0
    for x in arr:
        result += x
    return result

# Approach 2
def sum_2(arr):
    result = sum(arr)
    return result

# main function
if __name__ == "__main__":
    arr = [10, 20, 30, 40, 50]
    print ('sum_1: {}'.format(sum_1(arr)))
    print ('sum_2: {}'.format(sum_2(arr)))
```
