Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When to initialize an array with 256

Tags:

java

c++

arrays

I was looking through the cracking the coding interview book solutions and noticed the following problem:

Implement an algorithm to determine if a string has all unique characters. What if you can not use additional data structures?

This was one of the solutions provided:

public static boolean isUniqueChars2(String str) {
  boolean[] char_set = new boolean[256];
    for (int i = 0; i < str.length(); i++) {
      int val = str.charAt(i);
      if (char_set[val]) return false;
      char_set[val] = true;
    }
   return true;
 }

Why is the char_set array initialized with a size of 256? I was thinking that it was because there are 128 ascii characters but I'm not sure. Also, this solution seems to be in Java, but would an initial size also be necessary if this was done in C++?

like image 824
loremIpsum1771 Avatar asked Oct 01 '15 02:10

loremIpsum1771


People also ask

What is #define No_of_chars 256?

#define NO_OF_CHARS 256 // This function returns true if both arrays are same. // Irrespective of the size of patternText, this functions takes O(256) time i.e., O(1) time complexity.

Is it necessary to initialize the array?

You do not need to initialize all elements in an array. If an array is partially initialized, elements that are not initialized receive the value 0 of the appropriate type. The same applies to elements of arrays with static storage duration.

What is the initialize size of an array?

Array Initialization in Java To use the array, we can initialize it with the new keyword, followed by the data type of our array, and rectangular brackets containing its size: int[] intArray = new int[10]; This allocates the memory for an array of size 10 . This size is immutable.

Do you have to initialize the size of an array in Java?

Even if you do not initialize the array, the Java compiler will not give any error. Normally, when the array is not initialized, the compiler assigns default values to each element of the array according to the data type of the element. We will demonstrate these default values using the following program.


1 Answers

I was thinking that it was because there are 128 ascii characters but I'm not sure.

No. With extended ASCII codes, there are a total 256 characters. That's the reason for 256.

http://www.asciitable.com/

Apart from the reason given for 256, please note that com/

Note that as Erwin Bolwidt said, the code is at best incomplete in any case, because Java "characters" are not ASCII nor extended ASCII. They are "a 16-bit Unicode character", so the array should have been new boolean[65536]

like image 67
Suresh Atta Avatar answered Oct 03 '22 23:10

Suresh Atta