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

Array Java-01

There are several types of data structures including linear, tree, hash, and graphs structures. Linear structures include arrays and linked lists which store elements in a sequential manner. Linked lists are a collection of nodes that are connected via pointers, with each node containing a data field and pointer to the next node. Common operations on linked lists include creation, traversal, insertion, deletion, and searching of elements. [/SUMMARY]

Uploaded by

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

Array Java-01

There are several types of data structures including linear, tree, hash, and graphs structures. Linear structures include arrays and linked lists which store elements in a sequential manner. Linked lists are a collection of nodes that are connected via pointers, with each node containing a data field and pointer to the next node. Common operations on linked lists include creation, traversal, insertion, deletion, and searching of elements. [/SUMMARY]

Uploaded by

Chandan Mallesh
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 63

Data

Structure
Discuss.......

•What is data structure ?


• Why we have to use data structure ?
•Where we will use it ?
•How it is working ?
Data Structure

A data structure is a data organization, management, and storage format that


enables efficient access and modification.
Data Structure

How many types of data structure?


Data Structure

•Linear: arrays, lists


•Tree: binary, heaps, space partitioning etc.
•Hash: distributed hash table, hash tree etc.
•Graphs: decision, directed, acyclic etc.
Arrays

IN JAVA
Java 1D Array

● Array is a simple data structure used to store a collection of data in a contiguous block of
memory. Each element in the collection is accessed using an index, and the elements are
easy to find because they're stored sequentially in memory.
Java 1D Array

How many types of arrays in java? What is it ?

1. One dimensional (1-D) arrays or Linear arrays


2. Multi dimensional arrays
(a) Two dimensional (2-D) arrays or Matrix arrays
(b) Three dimensional arrays
Java 1D Array

Where can arrays be used in real life?


Java 2D Array

● You are given a 2D array. An hourglass in an array is a portion shaped like this:

abc
d
efg

● For example, if we create an hourglass using the number 1 within an array full of zeros, it
may look like this:
Actually, there are many hourglasses in the array
111000
above. The three leftmost hourglasses are the
010000
following:
111000
000000 111 110 100
000000 1 0 0
000000 111 110 100
Java 2D Array

111000
010000 111 110 100
111000 1 0 0
000000 111 110 100
000000
000000
Java 2D Array

● In this problem you have to print the largest sum among all the hourglasses in the array.

● Input Format: There will be exactly 6 lines, each containing 6 integers seperated by
spaces. Each integer will be between -9 and 9 inclusive.

● Output Format: Print the answer to this problem on a single line.

Sample Input: 111000


010000
111000
002440
000200 Sample Output:
001240
19
Java 2D Array

import java.io.*; int sum =


import java.util.*; a[i][j]
public class Solution{ + a[i][j-1]
public static void main(String[] args){ + a[i][j-2]
+ a[i-1][j-1]
int a[][] = new int[6][6]; + a[i-2][j]
int maxSum = Integer.MIN_VALUE; + a[i-2][j-1]
try (Scanner scanner = new + a[i-2][j-2];
Scanner(System.in);) if (sum > maxSum) {maxSum = sum;}
{ }
for(int i = 0; i < 6; i++){ }
for(int j = 0; j < 6; j++){ }
a[i][j] = scanner.nextInt(); }
if (i > 1 && j > 1) System.out.println(maxSum);
{ }
}
Java Subarray

● We define the following: A subarray of an n-element array is an array composed from a


contiguous block of the original array's elements. For example, if array=[1,2,3], then the
subarrays are [1],[2],[3],[1,2],[2,3], and [1,2,3]. Something like[1,3] would not be a subarray
as it's not a contiguous subsection of the original array.

● The sum of an array is the total sum of its elements.

● An array's sum is negative if the total sum of its elements is negative.

● An array's sum is positive if the total sum of its elements is positive.

● Given an array of integers, find and print its number of negative subarrays on a new line.
Java Subarray


Java Subarray

● Sample Input:

1 -2 4 -5 1

● Sample Output:

9
Java Subarray
Java Subarray

for(i=0;i<n;i++) {
import java.util.*;
if(a[i]<0){
public class Main{
count++;
public static void main(String[] args) {
} }
Scanner scan = new Scanner(System.in);
for(i=0;i<n;i++) {
int n = scan.nextInt();
for(j=0;j<i;j++) {
int a[] = new int[n];
sum = a[i] + sum; b[j] = sum;
int b[] = new int[n];
if(b[j]<0){
int count=0, i,j,sum = 0;
count++;
a[i] = scan.nextInt();
} }
} System.out.println(count); }}

for(i=0;i<n;i++) {
Java 1D Array

A left rotation operation on an array of size shifts each of the array's elements unit to the
left. For
example, if left rotations are performed on array , then the array would become.
Given an array of integers and a number, , perform left rotations on the array.
Input Format
● The first line contains two space-separated integers denoting the respective values of
(the number ofintegers) and (the number of left rotations you must perform).
● The second line contains space-separated integers describing the respective elements
of the array's initialState.
Java 1D Array

Sample Input
54
12345
Sample Output
51234
Java 1D Array

import java.util.*;
public class Solution {
public static void main(String[] args) {
Scanner scan = new Scanner(System.in);
int n = scan.nextInt();
int d = scan.nextInt();

int[] array = new int[n];


for(int i=0; i<n;i++) {
if(i-d < 0)
array[n+(i-d)] = scan.nextInt();
else
array[i-d] = scan.nextInt();
}
for(int i=0; i<n;i++) {
System.out.print(array[i] + " ");
}
}
}
QUESTION

Which of these operators is used to allocate memory to array variable in Java?

A)malloc
b)alloc
c)new
d) new malloc

Answer :
QUESTION

Which of these is an incorrect array declaration?


a) int arr[] = new int[5]
b) int [] arr = new int[5]
c) int arr[] = new int[5]
d) int arr[] = int [5] new

Answer :
QUESTION

What will be the output of the following Java code?


int arr[] = new int [5]; System.out.print(arr);
a) 0
b) value stored in arr[0]
c) 00000
d) Class name@ hashcode in hexadecimal form

Answer :
QUESTION

Which of these is an incorrect Statement?


a) It is necessary to use new operator to initialize an array
b) Array can be initialized using comma separated expressions surrounded by curly braces
c) Array can be initialized when they are declared
d) None of the mentioned

Answer :
QUESTION

Which of these is necessary to specify at time of array initialization?


a) Row
b) Column
c) Both Row and Column
d) None of the mentioned

Answer :
QUESTION

What will be the output of the following Java code?


class array_output {
public static void main(String args[]) {
int array_variable [] = new int[10];
for (int i = 0; i < 10; ++i) {
array_variable[i] = i;
System.out.print(array_variable[i] + " ");
i++; } } }
a) 0 2 4 6 8
b) 1 3 5 7 9
c) 0 1 2 3 4 5 6 7 8 9
d) 1 2 3 4 5 6 7 8 9 10

Answer :
QUESTION

What will be the output of the following Java code?


class evaluate {
public static void main(String args[]) {
int arr[] = new int[] {0 , 1, 2, 3, 4, 5, 6, 7, 8, 9};
int n = 6;
n = arr[arr[n] / 2];
System.out.println(arr[n] / 2);
} }
a) 3
b) 0
c) 6
d) 1
Answer :
QUESTION

What will be the output of the following Java code?


class array_output {
public static void main(String args[]) {
int array_variable[][] = {{ 1, 2, 3}, { 4 , 5, 6}, { 7, 8, 9}}; int sum = 0;
for (int i = 0; i < 3; ++i)
for (int j = 0; j < 3 ; ++j)
sum = sum + array_variable[i][j];
System.out.print(sum / 5);
} }
a) 8
b) 9
c) 10
d) 11
Answer :
LINKED-LIST

•Linked List is a very commonly used linear data structure which consists of group of nodes in a
sequence.
•Each node holds its own data and the address of the next node hence forming a chain like
structure.
LINKED-LIST

•Nodes in a linked list are connected by pointers.


LINKED-LIST AND ARRAY
LINKED-LIST AND ARRAY
LINKED-LIST AND ARRAY

Operations performed on arrays Operations performed on Linked List

•Creation of array •Creation

•Traversing an array •Traversing

•Insertion of new elements •Insertion

•Deletion of required elements. •Deletion

•Modification of an element. •Searching

•Merging of arrays •Concatenation


•Display
Types of Linked Lists

There are 3 different implementations of Linked List available, they are:

•Singly Linked List


•Doubly Linked List
•Circular Linked List
Singly Linked List

Singly linked lists contain nodes which have a data part as well as an address part i.e. next, which
points to the next node in the sequence of nodes.
The operations we can perform on singly linked lists are insertion, deletion and traversal
DOUBLY LINKED-LIST

● Doubly Linked List is a variation of the linked list. The linked list is a linear data

structure which can be described as the collection of nodes. Nodes are connected

through pointers

● Each node contains two fields: data and pointer to the next field

● The first node of the linked list is called the head, and the last node of the list is

called the tail of the list


DOUBLY LINKEDLIST

Data represents the data value stored in the node

Previous represents a pointer that points to the previous node

Next represents a pointer that points to next node in the list


DOUBLY LINKED-LIST

Memory Representation of a doubly linked list:

● Memory Representation of a doubly linked list is shown in the following image


● Generally, doubly linked list consumes more space for every node and therefore,
causes more expansive basic operations such as insertion and deletion
● However, we can easily manipulate the elements of the list since the list maintains
pointers in both the directions (forward and backward)
DOUBLY LINKED-LIST
DOUBLY LINKED-LIST APPLICATION

Each node in a double linked list has a pointer the previous and next node, it is easy to implement skip
forward/backward functionality
The pointer to the next node also makes it quite easy to start the next track when a track is over.
When you add a new track to a playlist, you tack it on to the end
DOUBLY LINKED-LIST

What is a memory efficient doubly linked list?

A. Each node has only one pointer to traverse the list back and forth
B. The list has breakpoints for faster traversal
C. An auxiliary singly linked list acts as a helper list to traverse through the doubly
linked list

D. A doubly linked list that uses bitwise AND operator for storing addresses

Ans:
DOUBLY LINKEDLIST

Which of the following operations is performed more efficiently by doubly linked list
than by singly linked list?

A. Deleting a node whose location in given


B. Searching of an unsorted list for a given item
C. Inverting a node after the node with given location
D. reversing a list to process each node

Ans:
DOUBLY LINKED-LIST

In linked list each node contain minimum of two fields. One field is data field to store
the data second field is?

A. Pointer to character
B. Pointer to integer
C. Pointer to node
D. Node

Ans:
DOUBLY LINKED-LIST

In doubly linked lists, traversal can be performed?

A. Only in forward direction


B. Only in reverse direction
C. In both directions
D. None

Ans:
DOUBLY LINKED-LIST

How do you calculate the pointer difference in a memory efficient double linked list?

A. head xor tail


B. pointer to previous node xor pointer to next node
C. pointer to previous node – pointer to next node
D. pointer to next node – pointer to previous node

Answer:
Q :01 Split a list into two halves in Java

Given a list, we need to split into two news lists in Java.

Input : list = {1, 2, 3, 4, 5, 6}


Output : first = {1, 2, 3}, second = {4, 5, 6}

Input : list = {1, 2, 3, 4, 5}


Output : first = {1, 2}, second = {3, 4, 5}
CODE:

public class Main {

// function to split a list into two sublists in Java


public static List[] split(List<String> list)
{

// find size of the list and put in size


int size = list.size();

// create new list and insert valuese which is returne by


// list.subList() method
List<String> first = new ArrayList<>(list.subList(0, (size) / 2));
List<String> second = new ArrayList<>(list.subList((size) / 2,
size));

// return an List of array


return new List[] { first, second };
}
CONTINUED…

public static void main(String[] args)


{
// create an ArrayList
List<String> list = new ArrayList<String>();

list.add("sam");
list.add("Practice");
list.add("Contribute");
list.add("IDE");
list.add("Callable");

// call split method which return List of array


List[] lists = split(list);

System.out.println(lists[0]);
System.out.println(lists[1]);
}
}
QUESTION :01

import java.util.*;
List<String> list2 = new
public class Main LinkedList<>();
{ list2.add("mac");
public static void
main(String[] args) list1.removeAll(list2); A. Mac
{
List<String> list1 = new for (String temp : B. breath
LinkedList<>(); list1)
list1.add("mac"); System.out.printf(te C. Lead
list1.add("breath"); mp + " ");
list1.add("lead"); D. Breath lead queen
list1.add("queen"); System.out.println();
}
}
Answer : D
QUESTION :02

import java.util.*;

public class stack


{
public static void main(String[] args)
{
A. SWEAK
List<String> list = new LinkedList<>();
B. For
list.add("SWEAK");
list.add("for"); C. SWEAK for
Iterator<Integer> iter = list.iterator(); D. Compilation Error
while (iter.hasNext())
System.out.printf(iter.next() +
" "); Answer : D

System.out.println();
}
}
QUESTION :03

import java.util.*; class A {


int i, j;
public class CollectionsTest { public A(int i, int j) A. L=5,S=4
{ this.i = i;
public static void this.j = j; B. L=4,S=3
main(String[] args) { }
List<A> l = new public A(int i) { C. L=3,S=3
ArrayList<A>(); this.i = i; }
l.add(new A(5, 4)); } D. Compiler
l.add(l.get(0));
l.add(new A(6, 0)); error
l.add(new A(5, 4));
l.add(new A(6));
Set<A> s = new
HashSet<A>();
s.addAll(l);
Answer : A
System.out.print("l = " +
l.size() + " s = " + s.size());
}
QUESTION :04

import java.util.ArrayList;

class Demo {
public void show()
{ A. True
ArrayList<String> list = new ArrayList<String>();
ArrayList<Integer> list1 = new ArrayList<Integer>(); B. False
boolean check = (list.getClass() ==
list1.getClass()); C. Compiler error
System.out.println(check);
} D. Run time error
} public class Main {
public static void main(String[] args)
{
Demo demo = new Demo(); Answer : A
demo.show();
}
}
QUESTION :05

class Demo { public class Main {


public void show() public static void
{ main(String[] args)
LinkedList<Integer> {
list = new Demo demo = new
LinkedList<Integer>(); Demo();
A. Compilation Error
list.add(1); demo.show(); B. 1 4 7 5
list.add(4); } C. 1 4 5 7
list.add(7); }
list.add(5);
for (int i = 0; i <
list.size(); i++) {
System.out.print(
list.get(i) + " ");
} Answer : B
}
}
QUESTION : 06

import java.util.*;
class Output
{ A. 3
public static void main(String args[])
{ B. 2
ArrayList obj = new ArrayList();
obj.add("A"); C. 1
obj.ensureCapacity(3);
System.out.println(obj.size()); D. 4
}
}

Answer : C
QUESTION :07

class Demo { public class Main {


public void show() public static void main(String[]
{ args) A. Compilation Error
ArrayList<String> list = new { cannot give
ArrayList<String>(); Demo demo = new Demo(); Collections.sort()
list.add("banana"); demo.show();
after Iterator.
list.add("apple"); }
Iterator itr = list.iterator(); } B. apple banana
C. banana apple
Collections.sort(list);
while (itr.hasNext()) {
System.out.print(itr
.next() + " "); Answer : B
}
}
}
QUESTION :08

import java.util.*;
class Main
{
public static void main(String[] args)
{ A. A
List < String > one = new ArrayList < String > ();
one.add("abc"); B. C
List < String > two = new Vector < String > ();
two.add("abc"); C. B
if(one == two) {
System.out.println("A");
D. None of the above
} else if(one.equals(two)) {
System.out.println("B");
} else {
System.out.println("C"); Answer : B
}
}
}
QUESTION : 09

import java.util.ArrayList; public class Main {


class Demo { public static void main(String[] A. Compilation
public void show() args) Error
{ {
ArrayList<Integer> list = new Demo demo = new Demo(); B. 4 7 1
ArrayList<Integer>(); demo.show(); C. 1 4 7
list.add(4); } D. None
list.add(7); }
list.add(1);
for (int number : list) {
System.out.print(number + " ");
} Answer : B
}
}
QUESTION :10

import java.util.ArrayList;
class Demo {
public void show()
{
ArrayList<String> list = new A. ArrayIndexOutOfBoundEx
ArrayList<String>();
System.out.print(list.get(0)); B. IndexOutOfBoundExcept
} C. null
} public class Main {
public static void main(String[] args)
{
Demo demo = new Demo(); Answer : B
demo.show();
}
}
QUESTION :11

import java.util.ArrayList;
A. German
class Demo {
public void show() B. Grey
{ C. Compilation error
ArrayList<String> list = new ArrayList<String>(); D. Run time error
list.add("German"); // line 6
list.add("Grey");
System.out.print(list.getFirst()); // line 8
}
}
public class Main { Answer : C
public static void main(String[] args)
{
Demo demo = new Demo();
demo.show();
}
}
QUESTION : 12

import java.util.LinkedList;

class Demo {
public void show()
{ A. null
LinkedList<String> list = new LinkedList<String>();
System.out.print(list.getFirst()); B. IndexOutOfBoundExcept
}
} public class Main {
C. NoSuchElementExceptio
public static void main(String[] args)
{
Demo demo = new Demo(); Answer : C
demo.show();
}
}
LINKED LIST

You are given two linked lists representing two non-negative numbers. The digits are stored in reverse order and
each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

Input: (2->4->3) + (5->6->4)


Output: 7 -> 0 -> 8

342 + 465 = 807

Make sure there are no trailing zeros in the output list


So, 7 -> 0 -> 8 -> 0 is not a valid response even though the value is still 807.

You might also like